As front-end developers, the stacks we are most familiar with are Vue and React, so I’ll share some of my own notes on how TO use Vue

Ref applies components and DOM

Ref is used on the DOM
<template>
    <div ref="refDom"></div>
</template>

mounted() {
  console.log(this.$refs.refDom);  // <div></div>
}
Copy the code

Ref is used on the DOM, so we can get the whole DOM element

Ref is used on components
<template>
    <div>
        <tree ref="refCompoent"></tree>
    </div>
</template>

mounted() {
  console.log(this.$refs.refCompoent);
}
Copy the code

Ref is used on a component to get an instance of the entire component

V – if and v – show

<template>
    <div>
        <div class ="show_dom" ref="refDom" v-show="showMe"></div>
    </div>
</template>

data () {
    return {
       showMe: false
    }
}
Copy the code

Elements shows that v-show is present in the DOM, but is not rendereddisplay:none;I’ve hidden it. I’ll add it heredisplay:none; opacity:0; visibilty:visible;The difference between:

  • Display: None causes the element to disappear completely from the render tree, taking up no space and not being clickable

  • Visibilty: Hidden does not make elements disappear from the render tree; render elements continue to occupy space, but the content is not visible and cannot be clicked

  • Opacity :0 Will not allow elements to disappear in the rendering tree, rendering elements continue to occupy space, but the content is not visible, can be clicked to inherit

  • Display: none and opacity: 0; The descendant node disappears because the child element disappears from the render tree and cannot be displayed by modifying the descendant node attribute

  • visibilty:hidden; Inheriting property, descendant node disappears because inheriting hidden by setting

  • visibilty:visible; You can have child element nodes show inheritance

  • Display: None: Modifying the display: None element will cause document rearrangement. The screen reader will not read the display: None element, which consumes high performance

  • Visibilty: Hidden: Modifying an element will only result in a redraw of the element. The screen reader reads the content of the Visibilty: Hidden element with less performance optimization
  • Any modification of elements causes redrawing, reducing performance consumption
<template>
    <div>
        <div class ="show_dom" ref="refDom" v-if="showMe"></div>
    </div>
</template>
Copy the code

Note that if v-if is used, there will be no DOM in the DOM tree, which will be commented out. If we need to switch DOM frequently, v-show is more appropriate, and vice versa

Parent and child component lifecycle hook function execution order

It can be divided into four parts:

First loading process

Parent Beroset => parent created => parent beforeMount

Child Beroset => Child created => children beforeMount => child Mounted => parent Mounted

The update process
Child component update process

Parent beforeUpdate => Child beforeUpdate => Child updated => Parent updated

Parent component update process

Parent beforeUpdate => Parent updated

Destruction of the process

Parent beforeDestroy => Child beforeDestroy => Child destroyed => Parent destroyed

Initial rendering process

  1. The parse template isrenderFunction (or completed in the development environment,vue-loader)
  2. Trigger reactive, listening for the data propertygetter setter
  3. Execute the render function to generatevnode, patch(elem, vnode)

The difference between computed and Watch

  • computed

  • Computed properties, depending on other properties, and when other properties change the next time you get computed values will change,computed values will be cached

  • watch

  • Similar to a callback after a data change

  • If you want deep listening, add a deep:true

  • Add an immediate:true if you want to run it immediately after listening

  • If you want to use watch in your life cycle

    this.$watch('someObject', callback, {
       deep: true,
       immediate: true
    }
    Copy the code

nextTick

  • NextTick: Perform a deferred callback after the next DOM update loop, and use this method immediately after modifying the data to get the updated DOM
  • If you want to create () DOM manipulation in a Vue lifecycle function, you can use the vue.nexttick () callback
  • NextTick is an operation that needs to be performed after the data has changed and the DOM structure has changed

After the next DOM update cycle ends, the delay callback is performed. NextTick mainly uses macro tasks and micro tasks, which are tried separately depending on the execution environment

  • Promise
  • MutationObserver
  • setImmediate
  • If none of the above fails, use setTimeout

Define an asynchronous method that clears the current queue by making multiple calls to nextTick to queue the method

Vue is asynchronous rendering and DOM does not render immediately after data changes

The $nextTick is captured after DOM rendering to get the latest DOM node

Routing patterns

Vue routing has three modes: hash, History, and Abstract

Hash: Uses the URL hash value for routing. All browsers are supported. The hash does not invoke interfaces

Hash pattern

Hash refers to the # at the end of the URL and the character at the end of the url. The # here is the same as the # in CSS. Hash, also known as the anchor point, is used for page positioning, and it can make the corresponding ID element visible. Since a hashchange does not cause the browser to make a request to the server, a hashchange event is triggered by a hashchange, and the browser can control it by moving forward or backward, front-end routing was mostly implemented using hash before the advent of HTML5 history

The nice thing about hash is that the hash appears in the URL but is not included in the HTTP request and has no impact at all on the back end, so changing the hash does not reload the page

Window.addeventlistener ('hashchange',function(){// Listen for hash changes, triggered when clicking browser forward or back})Copy the code
The history mode

The new pushState() and replaceState() methods in HTML5 History (browser-specific support required) apply to the browser’s History stack, the existing back, forward, and Go methods They provide the ability to modify the history, but when they change the current URL, the browser does not immediately send a request to the back end, so it can be said that the Hash mode and the history mode are browser features

Window.addeventlistener (' popState ',function(){// Listen for history changes, click browser forward or back})Copy the code
Difference between Hash and history

In hash mode, only the content before the hash symbol is included in the request, such as www.juejin.cn. Therefore, the back end does not return a 404 error even if the route is not fully covered

In history mode, the url of the front end must be the same as the ACTUAL URL of the back end. For example, www.juejin.cn/editor/ if the back end does not process /editor/, a 404 error is returned. In this case, you need to adjust the url of the back end

Router.query and router.params

Type get (query) and post (params)

The parameter is sent and received in query mode

The arguments:

this.$router.push({
       path:"/xxx"
       query:{ id:id}
   })
Copy the code

Receive parameters: this.$router.query.id

The params method is used to pass parameters

The arguments:

This $router. Push ({path: ". / XXX "params: {id: id}})Copy the code

Receive parameters: this.$router.params.id

  • Params can only use name:’ XXXX ‘in push, not path:’/ XXX ‘, because params can only use name to import routes. If path is used, the receiving parameter page will be undefined

  • Query is a get request. When a page jumps, you can see the request parameters in the address bar. Params is a POST request, and the parameters are not displayed in the address bar

  • If you refresh the current page, the data in the params object disappears, but the data in the Query object does not

  • This.$router and this.$route

$routeand$routerThe difference between

  • $route is a routing information object, including path, Params, Hash, Query, fullPath, matched, name and other routing information parameters.
  • $router is a route instance object that includes hop methods, hook functions, etc.

Virtual DOM

Simple and powerful VDOM library

Vue references its implementation of VDOM and DIff recommendations for learning

Mixin

  • Inside a data object

When the mixin data object conflicts with the component data, the component data takes precedence

  • Hook function

The hook function of the same name will be blended into an array and will be called, but the hooks blended into the object will be called before the component’s own hooks

  • Value is an option for the object

The options that are values for objects, such as Methods, Components, and directives, will be mixed into the same object and take the component object key-value pair if the two object keys conflict

How components communicate in VUE

  • Parent component passes to child component:data="tranData", the child component passespropsreceive
  • $refGets the child component instance
  • Use of child components$emitPass values to the parent component
  • The parent component passes$chidrenGet subcomponent instance subcomponent through$parentGets the parent component instance
  • vuexState management
  • Routing by value
  • througheventBusSibling components pass values
  • $attrsContains property bindings (except class and style)/ that are not recognized (and retrieved) by prop in the parent scope$listenersListeners that contain v-ON event listeners in the parent scope (without the.native modifier) can be passed into internal components via V-ON =”$Listeners”
  • provideandinject
  • LocalStorage and sessionStorage

Why must data be a function in a component

When a component is reused, a new data is returned, which means that each component instance has its own private data space and does not share the same data object

Proxy versus Object.defineProperty

Advantages of Proxy are as follows:

  • Proxies can listen directly on objects rather than properties
  • The Proxy can listen for changes to the array directly
  • Proxy has up to 13 intercepting methods, not limited to apply, ownKeys, deleteProperty, has, and so on that Object. DefineProperty does not have
  • Proxy returns a new Object, so we can just manipulate the new Object for our purposes, whereas Object.defineProperty can only be modified by iterating through Object attributes
  • Proxy as the new standard will be subject to ongoing performance optimization by browser vendors, which is also known as the performance bonus of the new standard

Object.defineproperty has the following advantages:

  • Good compatibility and support for Internet Explorer 9

The parent component listens for the life cycle of the child component

// Parent. Vue <Child @hook:mounted="doSomething"></Child> doSomething() {console. } // child.vue mounts () {console.log(' Child components trigger mounts... '); } // The child triggers the mounted hook function... // The parent listens to the mounted hook function...Copy the code

The @hook method not only listens for Mounted, but also for other lifecycle events, such as created, updated, etc

keep-alive

Keep-alive is a built-in component of Vue that can preserve the state of contained components and avoid re-rendering. It has the following features:

  • It is used together with routing and dynamic components to cache components.
  • provideincludeexcludeProperty, both of which support strings or regular expressions,includeIndicates that only components with matching names will be cached,excludeIndicates that any component whose name matches will not be cached, whereexcludeThe priority of include is higher than that of include
  • There are two hook functionsactivateddeactivatedWhen the component is activated, the hook function is triggeredactivatedTriggers the hook function when a component is removeddeactivated

Invoke asynchronous requests during the lifecycle

This can be done in created, beforeMount, and Mounted hook functions because data is created in these three hook functions and can be assigned to the data returned by the server. It is recommended to call asynchronous requests in created hook functions because created is created Calling an asynchronous request from a hook function has the following advantages:

  • In this way, data from the server can be obtained more quickly, reducing the loading time of the page
  • SSR is not supportedbeforeMountmountedHook function, so putcreatedTo help consistency

Listening for array changes

Object. DefineProperty does not listen for array changes

Rewrite definition prototype, rewrite push, pop and other methods, implement listening

Proxies can natively support listening for array changes

vm.$set

Solve the problem that the VUE view is not updated in time

this.$set( target, key, value )
Copy the code

Target: Data source to be changed (can be an object or array)

Key: The specific data to be changed

Value: indicates the reassigned value

Routing guard

Global Guards: beforeEach (to,from,next) and afterEach (to,from)

Exclusive guard of routes: beforeEnter

Components within the guard: routing beforeRouterEnter before you leave to enter/update / / update/leave vue routing guard hooks, vue way of routing, vue routing to participate

Route guard hook: Method used to execute route entry or exit

BeforeEach (to,from,next) : Front-guard of a route, accessing the method executed by the route

The parameter contains some information about the route

To: indicates the route to be entered

From: Indicates the exit route

Next: function that determines whether to display the routing page you want to see

next(); Smoothly into the

next(false); Block access to

next(‘/login’); Enter another route

Simple usage of global route guard:

The router. BeforeEach ((the to, from, next) = > {the if (to. The path = = '/ login' | | to. The path = = '/ register') {next ()} else {alert (' you are not logged in, Next ('/login')}})Copy the code

Local route guard:

BeforeRouteEnter (to, from, next) {this === undefined next(vm => {// use 'VM' to access component instance})}Copy the code

AfterEach (to,from) : Post guard of a route, leaving the route execution method

Common mode of VUE routing
  1. Dynamic route: Next to a route: Switches to the same component with different parameters

  2. Nested route: Level-1 routes are followed by children routes

  3. Programmatic routing: Push a new path in the router using JS

  4. Routing and the cords

  5. Use dynamic routing features: followed by the way of parameter passing

Definition:

{ path: '/user/:id', component: User }

Use:

this.$router.push({

 path: `/user/${id}`,

})
Copy the code

Access: this $route. Params. Id

  1. The matched route is determined by name in the route attribute, and the parameters are passed through params.

Definition:

{
    path: '/describe',
    name: 'Describe',
    component: Describe
}
Copy the code

Use:

this.$router.push({
    name: 'Describe',
    params: {
    id: id
    }
})
Copy the code

Access: this $route. Params. Id

  1. Using path to match routes and then passing parameters through Query is recommended

Definition:

{
    path: '/describe',
    name: 'Describe',
    component: Describe
}
Copy the code

Use:

this.$router.push({
    path: '/describe',
    query: {
    id: id
    }
})
Copy the code

Access: this $route. Query. Id

  1. Router-link declares params delivery
< the router - link: to = "{name: 'Reg, params: {num: 888}}" > show registration page < / router - the link >Copy the code

How to save login status with VUEX while refreshing

cookie

localstorage

The login token of the user is recorded locally. When entering the login page, the user sends a request to the back end to verify the validity of the token. How can the valid token enter the relevant page

  1. Record userMessage and token in vuEX

  2. During login, the user, token, and login identifier are recorded in the storage, and actions are sent to vuEX to change vuEX field values

  3. The state in vuEX will be initialized when the page is refreshed. Therefore, you need to determine the data in the local storage and send events through vuex to change the related status

A VUE route hook intercepts information about the current route and the route to be jumped during a route jump

The first is a global routing hook

beforeEach(to,from,next) {  
   //...
}
Copy the code

The second type: router exclusive hooks

beforeEnter(to,from,next) {
    // ...
}
Copy the code

Third: hooks within components

beforeRouteEnter(to,from,next) {
   //...
}
Copy the code
beforeRouteUpdate(to,from,next) {
  //...
}
Copy the code
beforeRouteLeave(to,from,next) {
// ...
}
Copy the code

Internal instructions

  • v-model: used to create two-way data binding on forms.
  • v-text: is equivalent to the JS text property
  • v-html: is equivalent to the innerHtml property of JS
  • v-show: Changes the implicit display through the style display
  • v-if: Renders elements based on true or false conditions for the value of an expression
  • v-else: v-else is used with v-if. It must be immediately followed by either v-if or v-else-if, otherwise it will not work
  • v-else-ifElse-if block: acts as v-if block, can be chained multiple times. Switch statements can be implemented more conveniently
  • v-slot: slot
  • v-once: only render once
  • v-pre: is used to skip compilation of this element and its children
  • v-cloak: used to remain on the element until it is compiled at the end of the associated instance
  • v-forRender according to traversal sets using the V-for command

Note: When v-for and V-if are on the same node, v-for has a higher priority than V-if. This means that v-if will run in each V-for loop

  • v-on: Binding event, abbreviated @
  • v-bind:Dynamically bind one or more featuresBound variable, abbreviated:

 <div :class="{'is-active':isActive, 'text-danger':hasError}"></div>
 <p :class="[{'is-active':activeClass},errorClass]">tg</p>
Copy the code

The modifier

.lazy

<input v-model.lazy="msg">
Copy the code

.number

<input v-model.number="msg">
Copy the code

.trim

<input v-model.trim="msg">
Copy the code

Event modifier

  • .native: Binding events can be executed on custom components
  • .stopStop the story from spreading
  • .preventEvents no longer reload the page
  • .captureUse the event capture pattern, where events triggered by the element itself are processed here before being processed by an internal element
  • .selfThe handler is fired only if the event.target is the current element itself
  • .onceThe event will only fire once
  • .passiveTell the browser that you don’t want to block the event’s default behavior

When using modifiers, order is important; The corresponding code is generated in the same order so v-on:click.prevent. Self blocks all clicks, whereas V-on :click.self. Prevent blocks only clicks on the element itself

Force rendering

The render function is not automatically updated. This.$forceUpdate() is used to re-render the virtual DOM, not reload the component, because this.$forceUpdat E After execution, only the beforeUpdate and updated hook functions are fired, and no other hook functions are fired. It only affects the instance itself and the child components that insert the contents of the slot, not all of them. This.$forceUpdate() can be manually refreshed

this.$forceUpdate()
Copy the code

To be updated…