1. Life cycle of Vue

  • beforeCreate : eldataNot initialized. You can’t get itpropsordataOf the data in
  • Created: Data that was previously inaccessible is already available, but the component is not yet mounted, so it is not visible.
  • BeforeMount: Starts creating the virtual DOM
  • Mounted: Renders the virtual DOM as the real DOM and renders data. If there are children in the component, they are loaded recursively, and only when all children have been mounted is the root component’s mount hook executed.
  • beforeUpdate: Executes immediately after the data of a component or instance changesbeforeUpdateAnd thenvueThe virtual DOM mechanism recreates the virtualdomWith the last virtualdomThe tree uses diff algorithm to compare and then re-render, generally do not do anything
  • updated: When the update is complete, executeupdated, the data has been changed,domAlso torenderComplete, you can operate the updated virtualdom
  • BeforeDestroy: Removes events and timers, otherwise memory leaks may be caused.
  • destroyedThe root component will be executed only after all subcomponents, if any, have been destroyeddestroyedHook function

In addition, keep-alive has unique life cycles, namely, activated and deactivated. Components wrapped with keep-Alive are not destroyed when switched. Instead, they are cached in memory and deactivated, and actived hooks are executed when cached. If you need to save the state of some components to prevent multiple renderings when switching components, you can use the keep-Alive component to wrap the components that need to be saved.

is an abstract component: it does not render a DOM element itself, nor does it appear in the parent component chain.

Keep-alive does not work properly in functional components because they have no cache instance. Keep-alive has three Props:

  • include– A string or regular expression. Only components with matching names are cached.
  • exclude– A string or regular expression. Any component with a matching name is not cached.
  • max– digital. Maximum number of component instances that can be cached.

Question:Keep aliveHow to update the data in

  • activatedTo change the data
  • beforeRouteUpdate

What is the order in which Vue’s parent and child lifecycle hooks are executed

  • Loading the render process

Parent beforeCreate-> parent created-> parent beforeMount-> child beforeCreate-> child created-> child beforeMount-> Child Mounted -> parent

  • Child component update process

Parent beforeUpdate-> child beforeUpdate-> child updated-> parent updated

  • Parent component update process

Father father beforeUpdate - > updated

  • Destruction of the process

Parent beforeDestroy-> child beforeDestroy-> child Destroyed -> parent Destroyed

2. Component communication

  • Parent-child communication
    • The parent component sends props to the child component, and the child component sends data to the parent component through the emit event

    • Methods and data in component instances are accessed by accessing $parent or $Children objects

    • $listeners and sync

      • Contains the parent scope (no.nativeModifier)v-onEvent listener. It can go throughv-on="$listeners" Passing in internal components— is useful when creating higher-level components
      • .syncModifier: It only exists as a compile-time syntactic sugar. It will be extended to automatically update the parent component propertiesv-onThe listener. When a child changes the value of a Prop, the change is synchronized to the parent binding

      Note that v-bind with the.sync modifier cannot be used with expressions (for example, v-bind:title.sync= “doc.title + ‘! ‘” is invalid). Instead, you can only provide the name of the property you want to bind to, similar to v-Model.

      • willv-bind.syncUsed on a literal object, for exampleV - bind. Sync = {" title: doc. Title}"Is not going to work because there are a lot of edge cases to consider when parsing a complex expression like this.
  • Sibling communication: this is achieved by finding the child components in the parent component, i.ethis.$parent.$childrenIn thechildrenCan be passed through the componentnameThe desired component instance is queried and then communicated
  • Communication across multi-tier components:provide/inject
  • Any component:vuex

3.computed and watch

  • computedIs to evaluate properties, rely on other properties to evaluate values, andcomputedThe value of is cached and is returned only if the calculated value changes.
  • watchWhen the value changes are heard, a callback is performed, in which some logical operations can be performed

Therefore, use computed when other properties are required to obtain values dynamically, and use Watch when complex business logic needs to be performed to listen to changes in values. Watch does not cache and can execute asynchronous methods

The principle of this is as follows: calculate properties VS listen properties

4. The difference between mixins and mixins

  • mixinUsed for global blending, which affects every component instance
    Vue.mixin({ beforeCreat(){ #... This method affects the beforeCreat hook function for each component}})Copy the code
  • mixins: If multiple components have the same business logic, you can strip out the logic and passmixinsMix in code, such as the logic to load data up and down. PS.mixinsThe mixed hook functions are executed before the component’s hook functions, and there is a selective merge of lines when an option with the same name is encountered.

5.AST

Vue will use the compiler to compile the template into the render function through several stages, and then execute the Render function to generate the Virtual DOM and finally map to the real DOM. There are three stages:

  • 1. Parse the template into AST: Use various regular expressions to match the content in the template, and then extract the content to do various logical operations, and then generate a basicASTobject
  • 2. Optimize the AST: Extract the nodes that will never change for reuseVirtual DOM, skip the function of the comparison algorithm
  • 3. Convert the AST torenderFunction: traverses the entireASTTo generate different code according to different conditions

Extension 1: Component update

  • At the heart of the component update process is the old and the newvnode diff, the new and old nodes are the same and different cases to do different processing. The different update processes for new and old nodes areCreating a new node->Update the parent placeholder node->Deleting an old node; The same update process is used to retrieve the new and old nodeschildren, do different update logic according to different situations. The most complex case is when the old and new nodes are the same and they both have child nodes, then it will be executedupdateChildrenlogic

Extended 2: Parse

  • Parse’s goal is to convert the Template string into an AST tree, which is a JavaScript object that describes the entire template. Therefore, the entire process of parse is to use the regular expression sequence parsing template, when the parse to the start tag, close tag, text will execute the corresponding callback function, to achieve the purpose of AST tree construction.

  • There are three types of AST element nodes: type 1 means a normal element, type 2 means an expression, and type 3 means plain text. In fact, HERE I think the source code is not friendly enough, this is a typical magic number, if converted into constant expression will be more conducive to source reading

The Diff algorithm:

  • Based on the real DOMvirtual DOMwhenvirtual DOMWhen a node’s data changes, a new node is generatedVnodeAnd thenVnodeandoldVnodeMake a comparison, find there are different places directly modify in the realDOMGo up and then makeoldVnodeThe value ofVnode
  • virtual DOMIs to extract the real DOM data, in the form of objects to simulate the tree structure
  • diffThe procedure is called by the namepatchFunction to compare old and new nodes, while comparing while giving the realDOMPatch.

When using diff algorithm to compare old and new nodes, the comparison will only be carried out at the same level, not across levels

The diFF flowchart is as follows

Reference link: in detail vue’s Diff algorithm

6. Vue bidirectional binding principle

Cn.vuejs.org/v2/guide/re…

  • depClass has two methods:addSub(Add dependencies) andnotify(Trigger update, call update method in watcher)
  • defineReactiveInitial initializationDepObject with recursive calls to child objectsobserveMethod, so as to ensure that no matterobjAll of its child properties can also become reactive objects that we can access or modifyobjOne of the more deeply nested properties can also triggergettersetter. The use ofObject.definePropertyLet’s go toobjThe properties of thekeyaddgetter(will bewatcherAdd to subscription, donedeptheaddSubMethod) andsetter(to performwatchertheupdateMethods)
Observe (obj, obj, obj, obj, obj, obj, obj, obj, obj, obj); obj||typeof obj! =='object'){ return } Object.keys(obj).forEach(key=>{ defineReactive(obj,key,obj[key]) }) }Copy the code

Presentation:

Var data={name:'aa'} observe(data) function update(value){var data={name:'aa'} observe(data) Document.queryselector ('div').innerText=value} new Watcher(data,'name',update)// Triggers the getter of the property to add listeners Data.name ='yyy'// Triggers the setter update for the propertyCopy the code

To address the problem that adding new properties to an object does not trigger a rerendering of the component, you can use a set method that does the following:

  • Determine whether it is an array and whether the subscript is valid — calltarget.splice(key,1,val)Method trigger updates
Function isValidArrayIndex (val) {var n = parseFloat(String(val)); Return n >= 0 && math.floor (n) === n && isFinite(val)//Math.floor(n) === nCopy the code
  • Determine if the key already exists, and if sotarget[key]=val
  • Assignment returns if the object is not reactivetarget[key]=val
  • Perform bidirectional data bindingdefineReactive(ob.value,key,val), manually dispatch updatesop.dep.notify()

To solve the problem that subscripting the array data does not trigger component rerendering, Vue internally rewrites some array functions to implement dispatch updates

B:Vue responsive Principle – How to listen for Array changes

  1. Get native firstArrayBecause after interception we still need the native method to help us implement the array changes.
  2. rightArrayThe prototype method is usedObject.definePropertyDo some interceptions.
  3. The ones that need to be interceptedArrayThe type of data prototype points to the modified prototype.

We’re going to modify the code, we’re going to pass the developer’s parameters to the native method, make sure that the array is changed the way the developer wants it to be, and then we’re going to update the view and so on.

7.Vue. Set and vm

  • Add a property to the responsive object and ensure that the new property is also responsive and triggers the view update.

  • It must be used for adding a new property to reactive object, because the Vue cannot detect common new property (such as this. MyObject. NewProperty = ‘hi’).

  • PS. Note that the object cannot be a Vue instance, or the root data object of a Vue instance

  • Usage:

    • For objects:
      • Vue does not allow dynamically adding root-level responses to an already created instanceproperty. However, it can be usedVue.set(object, propertyName, value)Method to add a response to a nested objectproperty
      • Sometimes you may need to assign multiple new values to existing objectsproperty, such as usingObject.assign()_.extend(). However, the new one that is thus added to the objectpropertyUpdates will not be triggered. In this case, you should use the original object and the object to be mixed inpropertyCreate a new object togetherthis.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
    • For arrays:
      • When setting an array entry directly with an index:Vue.set(vm.items, indexOfItem, newValue)orvm.items.splice(indexOfItem, 1, newValue)
      • When changing the length of an array: use splice–vm.items.splice(newLength)
  • B:

    setDistributed update
    • Queue scheduling
      1. Component updates from parent to child; Because the parent component is created before the child, sowatcherThe creation of is also late father after child, and the order of execution should remain late father after child.
      2. User customizationwatcherTake precedence over renderingwatcherImplementation; Because it’s user definedwatcherIs the renderingwatcherCreated earlier.
      3. If a component is in the parent component’swatcherIs destroyed during execution, then it corresponds towatcherExecution can be skipped, so the parent component’swatcherShould be executed first
    • Queue traversal
      • In thequeueAfter sorting, the next thing you need to do is go through it and get the correspondingwatcher, the implementation ofwatcher.run(). One thing to notice here is that it’s going to be correct every time you iteratequeue.lengthEvaluate, because inwatcher.run()It is likely that the user will add new ones againwatcher, which will again execute toqueueWatcher

8. How does front-end routing work? What is the difference between the two implementations?

Vue’s routing mode hash relies on window.onHashChange

Hash pattern The History mode
You can only change#What follows You can set any homologous URL through the API
The historical record You can only change the hash, which is the string You can add any type of data to the history
The back-end No back-end configuration is required for good compatibility When the user manually enters the address or refreshes the page, the URL request is initiated. You need to configure this function on the back endindex.htmlPages are used when static resources cannot be matched

The HTML5 History API adds an extension method to the browser’s global History object. Commonly used to solve the problem of ajax requests not being able to return to the state before the request by using the back button

In HTML5, the window.history object has been extended, with new apis including:

  • history.pushState(data[,title][,url])// Append a record to the history
  • history.replaceState(data[,title][,url])// Replace the current page in the history.
  • history.state// is an attribute that gives the current page state information
  • window.onpopstate// is an event inClick the browser back buttonOr * * js callsForward (), back(), go()Trigger when **. You can pass one in the listening functioneventObject,event.stateIs throughpushState()orreplaceState()Method is passed as the data parameter. Using history.pushState() or history.replacestate () does not trigger the popState event
Window.onpopstate = function(event) {console.log("location: "+ document.location + ", state: " + JSON.stringify(event.state)); }; history.pushState({page: 1}, "title 1", "? page=1"); history.pushState({page: 2}, "title 2", "? page=2"); history.replaceState({page: 3}, "title 3", "? page=3"); history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // Logs "location: http://example.com/example.html, state: null history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}Copy the code

See: In-depth Understanding of hash and History routing on the front end

9. The routing

  • this.$route.params:

Dynamic route matching

  • $routeand$router
    • $routeRepresents the current route information object
    • $routerObject: indicates a global route instancerouterExample of the constructor.
  • What are the route guards? The guard performs asynchronous resolution, where the navigation waits until all the guards have resolved.
  • Global navigation
    • beforeEach((to, from, next) => {// ... })(Global front guard) : Ensures that the next function is used in any given navigation guardCall it strictly once
    • beforeResolve(Global resolution guard) : Before the navigation is confirmed, at the same timeAll components inside guard and asynchronous routing componentsOnce parsed, the parse guard is called.
    • afterEach((to, from) => {//... })(global post-hook) : not acceptednextFunctions do not change the navigation itself
    • beforeEnter: (to, from, next) => {// ... }: Can be directly defined in route configurationbeforeEnterThe guards
  • A guard inside a component
    • beforeRouteEnter((to, from, next) => {// ... })The component instance has not been created before the guard executes. However, you can do this by passing a callback tonextTo access the component instance. Perform the callback when the navigation is confirmed, and take the component instance as a parameter to the callback method (supported fornext The only guard passing the callback)
    • beforeRouteUpdate((to, from, next) => {// ... }): is called when the current route has changed but the component is being reused to access the component instancethis
    • beforeRouteLeave((to, from, next) => {// ... }): is called when navigating away from the corresponding route of the component to access the component instancethis. Usually used to prevent users from abruptly leaving without saving their changes

Order of execution: Call beforeRouteLeave in inactive components > global call beforeEach> call beforeEnter in routing configuration > Resolve Asynchronous Routing Components > call in active components BeforeRouteEnter >beforeResolve> Navigation confirmed >afterEach> Trigger DOM update > Invoke the callback function passed to next in the beforeRouteEnter guard with the created instance

Extension 1: Vue-router principle

1. Implement a static install method, as plug-ins must have this method, for vue.use () to call 2. You can listen for route changes. 3. Resolve the configured route, that is, the routes configuration item of the router. Implement two global components router-link and router-view

Reference link: Vue-router Core implementation principle

Extension 2: front-end route permission control

Refer to this article: Vue Permission Control (Route Validation)

10. How do you react

React Vue
Using V-Model to support two-way binding, development is more convenient
Change the data format setState Changing the state is much simpler
Page update rendering It requires manual optimization by the user The underlying vue uses dependency tracking, and page updates are rendered optimally
Using JSX, you can completely control the page through JS, more flexible It uses template syntax, which is less flexible than JSX, but it is completely possible to get out of the toolchain and write render functions directly to run in the browser

11. What is a Virtual DOM? Why is the Virtual DOM faster than the native DOM?

First, manipulating the DOM is slow (because DOM is something that belongs in the rendering engine, and JS is something that belongs in the JS engine. When we are through the JS DOM operation, actually this operation involves communication between two threads, then it will bring some performance loss, DOM operation, the number of times a also is to have been conducting communication between threads, and manipulate the DOM may also bring redraw reflux, so also lead to performance problems), JS objects can be used to simulate and render the corresponding DOM, and by comparing the changes of the old and new nodes of the DOM (DOM is a multi-tree structure), the DOM can be locally updated to achieve performance optimization. There are other advantages after the first:

  • willVirtual DOMAs a compatibility layer, we can also interconnect with non-Web systems to achieve cross-end development
  • Again, passVirtual DOMWe can render to other platforms, such as implementationsSSR(server-side rendering), isomorphic rendering, etc
  • A high degree of abstraction of the implementation component

** The Internet says that real DOM is slower, but the test results show that it is faster than React. Why?

A: www.zhihu.com/question/31…

12. The MVC and MVVM

  • Traditional MVC architecture usually uses the controller to update the model, and the view retrives data from the model to render. When the user has input, the model is updated through the controller and the view is notified to update.
  • MVVM: IntroducedViewModelThe concept of.ViewModelOnly care about data and business processing, don’t careViewWhat to do with the data, in this case,ViewandModelCan be independent, either side changes do not necessarily need to change the other side, and can put some reusable logic in oneViewModelIn, let multipleViewReuse theViewModel

13.vuexthemutationandactionusage

  • mutation:
    • eachmutationBoth have a string event type (type) and a callback function (handler). This callback function is where we actually make the state change, and it takes state as the first argument
    • mutationIt must besynchronousfunction
  • Action
    • ActionIs submittedmutationInstead of changing the state directly.
    • ActionIt can contain anyasynchronousOperation.

14. Is introducednextTick

  • nextTickWe can do it next timeDOMA delayed callback is performed after the update loop ends to get the updatedDOM
  • $nextTick()Returns aPromiseObject, you can use the newES2017 async/awaitSyntax does the same thing:
methods: { updateMessage: Async function () {this.message = 'updated' console.log(this.$el.textContent) // => 'await' this.$nextTick() {this.message = 'updated' console.log(this.$el.textContent) // => 'await' this.$nextTick() Console. log(this.$el.textContent) // => 'updated'}}Copy the code

15. What are the design patterns and how to implement the VUE singleton pattern

Singleton patterns ensure that there is only one instance of a class and provide a global point of access to it

You can do this in two ways: classes and closures

Export function install (_Vue) {// Check whether the Vue. Use (Vuex) has been executed. If (Vue && _Vue === Vue) {if (process.env.node_env! == 'production') { console.error( '[vuex] already installed. Vue.use(Vuex) should be called only once.' ) } return } // If vue.use (Vuex) is executed for the first time, then the _Vue passed in is assigned to the defined variable Vue Vue = _Vue // Vuex initialization logic applyMixin(Vue)}Copy the code

When vue.use (Vuex) is executed, the install method is called, and the true Vue is passed as an argument. If vue.use (Vuex) is executed multiple times, the applyMixin(Vue) is executed only once. So there will be only one Store, which is the implementation of the singleton pattern in Vuex.

16. The Vue component v – model

//lovingVue is passed in to the prop named Checked. And when <base-checkbox> fires a change event with a new value, <base-checkbox v-model="lovingVue"></base-checkbox>Copy the code
Vue.component('base-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `
    <input
      type="checkbox"
      v-bind:checked="checked"
      v-on:change="$emit('change', $event.target.checked)"
    >
  `
})
Copy the code

Reference link: Custom event

17. Useful in the source codeobject.create(null)What does it do?

  • When you need a very clean and highly customizable object to use as a data dictionary
  • Want to savehasOwnPropertyA performance penalty and a little less code to slack off on

With the Object. The create (null)!!!! Otherwise, use {} references:

18.Vue.config.productionTip = false

Set to false to prevent Vue from generating a production prompt at startup

19. Optimize Vue performance

  • First consider the value, cost, and metrics of performance optimization
  • Performance optimization means, processes – detailed steps, with a quantitative description, such as how many requests were reduced, and what was the result
  • Vue application runtime performance optimization measures:
    • Introduced into the production environmentVuefile
    • Precompile templates using single-file components
    • Extracted componentCSSTo separate to file
    • usingObject.freeze()Improve performance
    • flatStoreThe data structure
    • Use persistence wiselyStoredata
    • Lazy component loading: juejin.cn/post/684490…
    • Delay buried point interface request
    • Increase the sw
    • Go to js preload unless first screen
    • Vue family bucket useCDNResources, and useNgnix ComboTo merge resources
      • withnginx_http_concat, to merge the requests in such a wayhttp://example.com/??style1.css,style2.css,foo/style3.cssAccess the merged resources. (Note 2 question marks)
      • The same directoryJSthroughNginx comboMerge, e.g.libsdirectoryvue.min.js,vue-router.min.js,vuex.min.jsMerge into a request download:
    https://cdn.abc.com.cn/libs/vue/vue_2.6.10/vue.min.js, libs/vue - the router/router_3. 1.3 / vue - router. Min. Js, libs/vuex/vuex_3. 1. 1/vuex.min.jsCopy the code
    • Bury and share components and non – first – screen third partiesJSOn the pageonloadLoad after event
    • Third party dependencies do not participate in packaging:
      config.externals = {
      vue: 'Vue',
      vuex: 'Vuex',
      'vue-router': 'VueRouter',
       axios: 'axios'
      }
      Copy the code
  • Vue Measures for optimizing application loading performance
    • Server render/pre-render
    • Component lazy loading
  • Analyze js package size using Webpack-bundle-Analyzer

Reference: Vue Application Performance Optimization Guide

20. The modifier

  • Event modifier
    • .stop: prevents bubbling behavior and prevents events of the current element from continuing to be triggered externally, such as preventing clicking events inside div from being triggereddivThe event
    • .prevent: Prevents the action of the event itself, such as preventing the click jump of a hyperlink,formClick submit of the form
    • .capture: is to change the js default event mechanism, default is bubbling,captureThe function is to change bubbling to listening mode
    • .self: will only be executed if it is triggered by itself. If it receives an internal bubble event signal, it will be ignored
    • .once: yes Sets the event to be executed only once, for example.click.prevent.once The representative blocks the default action of the event only once, and the action of the event itself is executed a second time..onceModifiers can also be used on custom component events
    • .passive: The default behavior of the scroll event (i.e., the scroll behavior) will be triggered immediately, without waitingonScrollTo complete. this.passiveModifiers in particular can improve performance on mobile.

PS:.passive and.prevent cannot be used together:.prevent will be ignored

  • Key modifier
    • VueTo allow forv-onAdd key modifiers when listening for keyboard events: for example<input v-on:keyup.enter="submit">
    • You can just putKeyboardEvent.keyAny exposed valid key name is converted tokebab-caseAs a modifier. Such as:<input v-on:keyup.page-down="onPageDown">The processing function will only be in$event.keyIs equal to thePageDownCalled when
  • System modifier
    • .ctrl,.alt,.shift,.meta,.exact,.left,.right,.middle

21. Vue force update

  • this.$forceUpdate(): forces the Vue instance to re-render. Note that it only affects the instance itself and the child components inserted into the slot contents, not all child components.
  • withObject.assign

OldObj = object.assign ({},newObj); When we create an object and assign it to the oldObj field, we change the address of the object. When we create an object and assign it to the oldObj field, we change the address of the object

  • Vue.set

22.Custom instruction

A directive definition object can provide the following hook functions (all optional) :

  • bind: is called only once, the first time a directive is bound to an element. This is where you can do one-time initialization.
  • inserted: called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but not necessarily has been inserted into the document).
  • update: of the componentVNodeCalled on update time, but may occur on its childrenVNodeBefore the update. The value of the instruction may or may not have changed. But you can ignore unnecessary template updates by comparing the values before and after the update
  • componentUpdated: of the component where the directive residesVNodeAnd his sonVNodeCalled after all updates.
  • unbind: is called only once, when the instruction is unbound from the element.

The parameters to the hook function are EL, binding, vnode, and oldVnode