Introduction to the

Readers are expected to build their own knowledge tree (mind map)

Lazy: Refer to my own summary mind map: click here

Bonus: Frequent interview question accumulation documentation. From (senior students, Niuke.com and other platforms)

I developed my blog address: zxinc520.com

Github address: Click

The interview is very easy.

My blog [MVVM and VUE] reference address: address

My blog [virtual DOM] reference address: address

The virtual DOM

What is the virtual DOM

  • Virtual DOM
  • Simulate the DOM structure with JS
  • Comparison of DOM variations, done in the JS layer (Turing-complete language)
  • Advantages: Improved redraw performance

2. The significance of the existence of virtual DOM

  • DOM manipulation is “expensive”
  • DOM comparison operations in the JS layer, improve efficiency
  • The more complex the project, the more severe the impact

3. How to apply VDOM and what is the core API?

  • Introduce snabbdom
    • Snabbdom: a vDOM implementation library.
  • Core API
    • H function
    • The h function is the function that generates the virtual DOM
    • H (‘< tag name >’, {… Attribute… }, [… child element…] )
    • H (‘< tag name >’, {… Attribute… }, [‘…. ‘])
    • The patch function
      • Diff algorithm is used to compare the difference between the old VNode and the new VNode and then Patch Operation or Patch function is performed to update the Dom node efficiently.
      • Patch (Container, vnode)
      • Patch (vnode, newVnode)

4. Introduce the DIFF algorithm

  • Introduction to the

    • Diff algorithms have always been around, not invented by Vue and React
  • Why does VDOM use diff algorithm

    • DOM manipulation is “expensive,” so keep DOM manipulation to a minimum
    • Find the nodes whose DOM must be updated this time and do not update the rest
    • The process of “finding out” requires the diff algorithm
  • Diff implementation process

    • Patch (Container, vnode)

      • Core logic createElment

        function createElement(vnode) {
            let tag = vnode.tag
            let attrs = vnode.attr || {}
            let children = vnode.children || []
            let elem = document.createElement(tag)
            for (let attrName in attrs) {
                if (attr.hasOwnProperty(attrName)) {
                    elem.setAttribute(attrName, attrs[attrName])
                }
            }
            children.forEach((childVnode) = > {
                elem.append(createElement(childVnode))
            })
            return elem
        }
        
        Copy the code
    • Patch (vnode, newVnode)

      • Core logic updataChildren

        function updateChildren(vnode, newVnode) {
            let children = vnode.children || []
            let newChildren = newVnode.children || []
            children.forEach((child, index) = > {
                let newChild = newChildren[index]
                if (newChild == null) {
                    return
                }
                if (child.tag === newChild.tag) {
                    updateChildren(child, newChild)
                } else {
                    replaceNode(child, newChild)
                }
            })
        }
        Copy the code
  • What about diff?

    • Know what the diff algorithm is, the basic command of Linux
    • The purpose of applying diff algorithm in VDOM is to find the nodes that need to be updated
    • Diff implementation: patch (container, vnode) and patch (vnode, newVnode)
    • Core logic, createElment and Update dren

Ii. Vue knowledge summary

5. The difference between frameworks and libraries

  • Ibrary (library)
    • Small, clever libraries that only provide specific apis; The advantage is that the boat is small and easy to turn around. Easy to switch from one library to another; But the code hardly changes.
  • The Framework (Framework)
    • The big and complete is the frame; The framework provides a complete set of solutions; So, if you want to switch to another framework in the middle of a project, it can be difficult.
  • Talk about the difference between using jQuery and using frameworks
    1. Separation, decoupling of data and view (Open closed principle)
    2. VUE is data-driven and only cares about data changes, while DOM operations are encapsulated

6. Vue vs. Angular and React

  • Vue and presents
    • AngularJS is expensive to learn, such as adding Dependency Injection, while vue.js provides simple and intuitive apis. In terms of performance, AngularJS relies on data being dirty checked, so the more Watcher you have, the slower it is; Vue.js uses dependency tracing based observations and uses asynchronous queue updates, where all data is triggered independently.
  • Vue and React
    • React uses the Virtual DOM to do dirty checks on rendered results; Vue.js provides instructions and filters in the template, which can be very convenient and fast to operate Virtual DOM.

7. Overview of Vue

  • What is the Vue
    • Is a progressive JS framework for building user interfaces
  • where
    • Small to simple form processing, large to complex data manipulation more frequent single-page applications
  • Why VUE
    • Data driven
    • componentization
  • Way to work
    • You can extend templates with rich instructions, and you can enhance functionality with a variety of plug-ins

8. MVVM framework mode

  • concept
    • MVVM is short for model-view-viewModel. The software architecture design pattern is an event-driven programming approach that simplifies user interfaces.
  • Per-letter parsing
    • Model stands for data Model
    • View stands for View, which is responsible for turning the data model into a UI for presentation
    • Connect Model and View, which is an object that synchronizes the View and the Model

9. Vue three elements *

9.1. Responsiveness: How does VUE monitor every property change of data?

What tasks do Observe, DEP and Wather share in the response

[observe class] [DEP object] [wather performer] — Make it clear

  • What is the Vue response

    • The data property is proxied to the VM
  • Object.defineproperty (Two-way data binding)

    • define
      • The object.defineProperty () method directly defines a new property on an Object, or modifies an existing property of an Object, and returns the Object.
    • Disadvantages why Vue3. X upgrade uses Proxy instead of Object.defineProperty
      • Object. DefineProperty cannot monitor array subscript changes, resulting in adding elements by array subscript and cannot respond in real time.
      • Object.defineproperty can only hijack attributes of an Object, which requires traversal of each Object, each attribute, and deep traversal if the attribute value is an Object. A Proxy can hijack an entire object and return a new object.
      • Proxy can Proxy not only objects, but also arrays. You can also proxy dynamically added properties.
  • Data property change process

    1. Modify properties that are listened on by a reactive set
    2. Set updataComponent (asynchronous)
    3. UpdataComponent reexecute vm.render()
    4. The generated vNode and prevVnode are compared by patch
    5. Render to HTML
  • How does a simulation implementation Vue listen for data

    let vm={}
    let data={
        name:'zc'.age:'12'
    }
    for(let key in data){
        if(data.hasOwnProperty(key)){
            Object.defineProperty(vm,key,{
                get:function () {
                    return data[key]
                },
                set:function (newValue) {
                    data[key] = newValue
                }
            })
        }
    }
    Copy the code

9.2 Template engine: how are vUE templates parsed and instructions processed?

  • What is the template?
    • Nature: String
    • Logic, such as V-if, V-for, etc
    • Much like HTML, but with a big difference
    • Eventually it will be converted to HTML for display
  • Templates must eventually be converted to JS code because
    • Has logic (V-if, V-for), must be implemented with JS (Turing complete)
    • To convert HTML to render pages, you must use JS
    • Therefore, it is important to convert the template to a RENDER function.
  • How are templates parsed in VUE
    • An overview of the
      • The template must be converted to the Render function (the first step of compilation is to parse the template into an AST (abstract syntax tree) using the parse function, the second step is to optimize the AST (to detect a purely static subtree of the DOM that does not need to be changed), and the third step is to generate objects containing the render function strings from the optimized abstract syntax tree).
      • specific
        1. The first step is to parse the template into an AST (abstract syntax tree) using the parse function
          • Parse to AST: parse function
          • In the process of parsing the template, various hook functions are constantly triggered, and the node information is passed to the AST builder of vue.js through the start, end, and chars, comment methods. The AST of the template is built simultaneously while parsing.
        2. Step 2 Optimize AST (detect pure static subtrees of DOM that do not need to change)
          • Optimize AST: optimize function
        3. The third step is to generate an object containing the render function string from the optimized abstract syntax tree.
          • Generate render function: generate function

9.3 render: How are vue templates rendered to HTML? And the rendering process

  • Render function and VDOM

    • Vdom generation patch is implemented in updataComponent

    • Perform updataComponent for the first rendering of the page

    • Render function – with

      • conclusion

        • All the information in the template is contained in the render function
        • This is the vm
        • Price is this.price is vm. Price, which is the price in data
        • _c is this. _c is vm. _c
      • use

        / / to use with
        function fn1() {
            with (obj) {
                console.log(name)
                console.log(age)
                getAddress()
            }
        }
        Copy the code
    • Each time an attribute is modified in data, run updataComponent

10. The entire implementation process of VUE?

  • Step 1: Parse the template into the Render function
  • Step 2: Start listening in a responsive manner
  • Step 3: Render for the first time, display the page, and bind dependencies
  • Step 4: Data property changes, rerender is triggered

11. Vue life cycle

  • What is the life cycle
    • The lifecycle of a Vue instance is the process from creation to destruction. We call this the life cycle of a Vue, which starts with creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and unmounting.
  • role
    • It has multiple event hooks throughout its lifecycle, making it easier to form good logic when controlling the process of an entire Vue instance.
  • How many phases are there in the VUE life cycle?
    • It can be divided into 8 stages altogether: before/after creation, before/after load, before/after update, and before/after destruction
  • Which hooks are triggered the first time the page loads?
    • BeforeCreate, Created, beforeMount, and Mounted are triggered the first time a page is loaded
  • Describe briefly what scenarios are appropriate for each cycle?
    • Beforecreate: You can add a loading event here, which is triggered when the instance is loaded
    • Created: This is where the initialization event is written. For example, this is where the loading event ends and asynchronous requests are called
    • Mounted: A DOM node is obtained after an element is mounted
    • Updated: If data is treated uniformly, write the corresponding function here
    • BeforeDestroy: Can make a confirmation box to confirm stop events nextTick: Update data immediately after manipulation of the DOM
  • Hook function
    1. BeforeCreate: The component instance was just created, and the data in data and Methods is not initialized
    2. Created: Component instance is created, data and methods are initialized! But the DOM hasn’t been generated yet
    3. BeforeMount: before a template is compiled or mounted
    4. Mounted: Indicates that a template is compiled or mounted
    5. BeforeUpdate: Before a component is updated
    6. Updated: After the component is updated
    7. BeforeDestroy: Called before component destruction
    8. Destroyed: Called after the component is destroyed

12. Communication between Vue components (father, brother, grandchild, etc.)

Six kinds of way

  1. props/$emit

    • Parent component A passes props to child component B, and B to A is realized by $emit in component B and V-on in component A.
    • Application scope: Parent and child components
  2. on

    • This approach uses an empty Vue instance as the central event bus (event hub) to trigger and listen for events, subtly and lightly enabling communication between any component, including parent, sibling, and cross-level. When our project was larger, we could have chosen a better state management solution, VUEX.

    • Concrete implementation mode

       var Event=newVue(); $emit(Event name, data); $on(data => {});Copy the code
    • Scope of application: including father and son, brother, cross level

  3. vuex

    • Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.
  4. listeners

    • When multi-level component nesting needs to pass data, the common method used is through VUEX. But if you’re just passing data around without intermediate processing, using VUex is a bit overkill. An alternative approach to this is provided for Vue2.4 at —-listeners
  5. provide/inject

    • To allow an ancestor component to inject a dependency into all its descendants, no matter how deep the component hierarchy is, for as long as the upstream and downstream relationship is established.
  6. Children with the ref

    • Downside: The downside of both methods is that there is no way to communicate across levels or siblings.

Common usage scenarios can be divided into three categories

  • Parent-child communication
    • The parent passes data to the child through props, and the child passes data to the parent through events (parent / attrs/$listeners
  • Brother communication
    • Bus; Vuex
  • Across the communication level
    • Bus; Vuex; Provide/Inject API,listeners

13, Vuex

  • define

    • Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.
  • The basic idea behind Vuex

    • The shared state of the components is extracted and managed in a global singleton mode. In this mode, our tree of components constitutes a huge “view” where any component can obtain state or trigger behavior no matter where in the tree!
  • Vuex differs from a purely global object in two ways

    1. Vuex’s state storage is reactive.
    2. You can’t just change the state in the store. The only way to change the state in the store is to commit mutation explicitly. Because we want to track state changes more explicitly.
  • The composition of vuex

    1. state

      • Vuex uses state to store the state that needs to be shared across applications. In order for the Vue component to change after state changes, you need to create computed properties based on state.
    2. getters

      • The return value of the getter is cached based on its dependency, and is recalculated only if its dependency value changes
    3. Mutations

      • Mutations are the executor of a change of state, and mutations are used to change a state simultaneously

        store.commit({
          type: 'increment'.amount: 10   // This is an extra parameter
        })
        Copy the code
    4. Actions (asynchronous)

      • To change state asynchronously, the action does not change state directly, but initiates mutation

        // Distribute as objects
        store.dispatch({
          type: 'incrementAsync'.amount: 10
        })
        Copy the code
        // Distribute in payload form
        store.dispatch('incrementAsync', {
          amount: 10
        })
        Copy the code
    5. Module: Modular store

      • Problems arising
        • Because of the use of a single state tree, all the states of an application are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated.
      • The solution
        • Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules

Vuex workflow

  1. Data is rendered from state to the page
  2. Trigger the action via Dispatch on the page
  3. Action triggers mutation by calling COMMIT
  4. The deP object is notified of the mutation and all Watcher objects are notified to modify the corresponding view (vUE).

Application scenarios

  • Multiple views depend on the same state
  • Actions from different views need to change the same state

14. Vue routing (VUe-router)

Vue routing implementation principle [must be clear]

  • vue-router

    • Vue – what is the router

      • Vue Router is the official route manager of vue. js
    • Which components

      1. <router-link >

      2. <router-view>

      3. <keep-alive >

        • define

          • Keepalive is a component built into Vue that can keep contained components in state or avoid re-rendering. This is known as —– component caching
        • Component caching

          • Use the include/exclude

            • include
            • exclude
          • Add the router.meta attribute

            meta: {
                  keepAlive: true // Need to be cached
                }
            Copy the code
        • Activated Fires when the keepalive component is rendered again

        • Deactivated Triggered when a keepalive component is destroyed

  • Dynamic routing

    • Create: The dynamic path argument, starting with a colon, is used mainly when using the path attribute

    • Responds to changes in routing parameters

      1. this.$route.params

      2. Watch (monitoring changes) $route object

        watch: {
          $route(to, from) {console.log(to.path)
            // Respond to routing changes}}Copy the code
      3. Use the beforeRouteUpdate navigation guard introduced in 2.2

  • Embedded routines by

    • The children configuration is required in the parameters of the VueRouter
  • navigation

    • declarative

      <router-link :to="...
      Copy the code
    • programmatic

      router.push(...)
      Copy the code
  • Redirects and aliases

    • redirect

      routes: [
          { path: '/a'.redirect: '/b'}]Copy the code
    • The alias

      routes: [
          { path: '/a'.component: A, alias: '/b'}]Copy the code
  • Two modes of vue-Router

    • Hash mode (default)
      • Principle: The principle is the onHashchage event, which can be listened on the window object
      • Description: Dynamically render the page by adding the # + route name after the link and triggering the Hashchange event based on the matching field changes.
    • The history mode
      • Description: Takes advantage of the new pushState() and replaceState() methods in the HTML5 History Interface.
      • disadvantages
        1. Background configuration support is required
        2. If the server does not respond to a resource when refreshing, a 404 will appear
  • Navigation hook function (navigation guard)

    • Navigation indicates that the route is changing.
    • role
      • Vue-router provides navigation guards that are used to guard navigation by jumping or canceling. There are several opportunities for embedding route navigation: global, single route proprietary, or component level
    • What are the navigation guards
      1. Global front guard
        • router.beforeEach
      2. Global Parsing Guard (new in 2.5.0)
        • router.beforeResolve
      3. Global post-hook
        • afterEach
        • Unlike guards, these hooks do not accept the next function or change the navigation itself:
      4. Route exclusive guard
        • BeforeEnter guard
      5. Guards within components
        1. BeforeRouteEnter: called before the corresponding route to render the component is confirmed
        2. BeforeRouteUpdate: Called when the current route has changed but the component is being reused
        3. BeforeRouteLeave: called when navigating away from the corresponding route of the component
    • Related topics
      1. What is vue-router? What are the components?
      2. Active-class is a property of which component?
        • Active-class is a router-link terminal property used to toggle the selected styles that will be applied when the router-link tag is clicked
      3. How to define a vue-router dynamic route? How do I get the passed value?
      4. What kinds of navigation hooks does vue-Router have?
      5. What is the difference between a Router?
        • The Router is an instance of the VueRouter. It is a global routing object that contains hop methods, hook functions, and so on
        • Route is routing information object | | jump route objects, each object of a route is a route, is a local object that contains the path, params hash, query, fullPath, matched, routing information parameters such as the name.
        • The pass parameter is this.router and the receive parameter is this.route
      6. Vue-router responds to route parameter changes
      7. Vue – the router to participate
      8. Two modes of vue-Router
      9. Vue-router Implements lazy route loading (dynamic route loading)
        • Dividing the components corresponding to different routes into different code blocks and loading the corresponding components only when the routes are accessed is lazy loading of routes, which can accelerate the loading speed of projects and improve efficiency

15, a Mixin

  • What is a Mixin
    • A very flexible way to distribute reusable functionality in Vue components.
  • When to use Mixins
    • The style of the page is different, but the method is similar to the data required.

16. Vue instruction

  • Custom instruction
    • Vue.directive
  • Customize a filter
    • Vue. Filter (‘ filter name ‘,function(){})

Interview questions that can be answered in one sentence

  1. CSS only works on the current component
    • Just write scoped in the style tag. For example: <style scoped></style >
  2. V-if is different from V-show
    • V-if renders according to conditions, v-show is block or none of display;
  3. What are the two cores of vue.js?
    • Data driven, component systems
  4. Vue several common instructions
    • V-for, V-if, V-bind, V-ON, V-show, v-else
  5. Vue common modifiers?
    • Prevent: Submit events that no longer reload the page; . Stop: prevents the click event from bubbling. .self: Fires when an event occurs in the element itself rather than a child element; .capture: event listening, called when an event occurs
  6. Can V-ON bind multiple methods?
    • can
  7. * What is the function of the key value in vUE?
    1. A more accurate
      • When vue.js is updating a rendered element list with V-for, it defaults to a “reuse in place” strategy. Using keys avoids in-place reuse. So it’s more accurate
    2. faster
      • The uniqueness of key is used to generate map objects to obtain corresponding nodes, which is faster than traversal
  8. What are the calculated properties of vUE?
    • Putting too much logic into a template can make the template too heavy and difficult to maintain, so try to compute attributes in cases where complex processing of data is required and may be used multiple times.
    • benefits
      1. Make the data processing structure clear
      2. Depend on data, data update, processing results update automatically
      3. Inside the compute attribute this points to the VM instance
      4. In the template call, just write the computed property name
      5. Getter methods are commonly used to get the data, or you can change the data using a set method
      6. Compared with methods, methods recalculates regardless of the dependent data, but computations obtained from the cache do not recalculate when the dependent data does not change
  9. Vue and other single page applications (SPA) and their advantages and disadvantages
    • advantages
      1. User experience is good, fast, content change does not need to reload the whole page, avoid unnecessary jump and repeated rendering;
      2. Based on the above point, SPA exerts less pressure on the server
      3. The responsibilities of the front and back end are separated, and the architecture is clear. The front end carries out interactive logic, and the back end is responsible for data processing.
    • disadvantages
      1. Browsers of earlier versions are not supported. Internet Explorer 9 at least is supported.
      2. The first time to load the home page is relatively long
      3. You can’t use the browser’s navigation buttons. You need to move forward and backward.
      4. Not conducive to SEO optimization (to support SEO, it is recommended to render components via the server side)
  10. Vue’s parent and child component lifecycle hook functions are executed in sequence
    • Loading the rendering process
      • Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted
    • 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
  11. Why is data a function in a Vue component?
    • If data is an object in a component, then the scope is not isolated. The data property values in the subcomponent will affect each other. If the data option in a component is a function, then each instance can maintain an independent copy of the returned object. Data property values between component instances do not affect each other; The instance of new Vue is not reused, so there is no object reference problem