Vue interview questions (three stages)

Day01

1. The principle of responsiveness

The principle of vue2 responsiveness is to use data hijacking and publish subscriber mode

① Data hijacking:

Purpose: To be able to perceive changes in data.

Data hijacking is: using ES5's Object.defineProperty(). Traversing all the data in the data configuration item and converting it into setter and getter (or in other words, adding set and get functions to each property) is: accessor property.

②Publish subscriber mode:

Purpose: When data changes, (directly and indirectly) there will be corresponding changes in the templates that use the data (templates will be re-rendered).

Maybe the other party will ask further: Can you be more specific. how to answer?
      1)
In the Vue constructor, loop through all attributes in the variable data. First, save the value of the property, and then use Object.defineProperty() to add set and get methods to each property. Then, each property requires a subscription object, traverse the dom tree, and have all dom elements that use that property subscribe to that property.
      2) When modifying the value of a property, the set function of the property is called, and all subscribers (functions) that subscribe to the property are called at the same time

class Vue {
    constructor(obj) {
        this.$el = obj.el;
        this.$data = obj.data;
        // 2.1、订阅(暂时写死,只订阅msg的变化)
        let observer1 = new Observer();
        observer1.addSubscribe(function (newVal) {
            document.getElementById("p01").innerHTML = newVal;
            document.getElementById("p02").innerHTML = newVal;
            document.getElementById("p03").innerHTML = newVal;
            console.log(newVal);
        });
        // 把data中的属性赋给this对象
        for (let key in obj.data) {
            // 保存数据(data中的每个属性的数据)。
            let value = obj.data[key];
            // 2.1、订阅(应该放在此处)
            // 1、数据劫持。
            Object.defineProperty(this, key, {
                set: function (val) {
                    console.log("val", val);
                    if (value == val) {
                        return;
                    }
                    value = val;
                    // 2.2、发布(更新使用key的dom元素)
                    observer1.publish(val);
                },
                get: function () {
                    return value
                }
            })
        }
        console.log("this", this);

        this.render();
    }
    render() {
        // this.$el
        let htmlStr = document.querySelector(this.$el).innerHTML;

        for (let key in this.$data) {
            htmlStr = htmlStr.replaceAll("{
   
   {" + key + "}}", this.$data[key]);
        }
        document.querySelector(this.$el).innerHTML = htmlStr;
    }
}
// 发布订阅模式的代码。
class Observer {
    constructor() {
        // 存放所有的订阅
        this.arr = [];
    }
    // (添加)订阅
    addSubscribe(cb) {
        this.arr.push(cb);
    }
    // 发布
    publish(what) {
        this.arr.forEach(cb => {
            (typeof cb === "function") && cb(what);
        })
    }
}

Two, the difference between v-if and v-show

Same point:

(All control the display and hiding of dom elements)

difference:

①The principle is different:
     v-if is to complete the display and hiding through the deletion and addition of dom elements,

     ​ v-show completes displaying and hiding by modifying the value of the style attribute display.

② Different
      v-if of performance consumption: performance loss is mainly reflected in frequent switching

     ​ v-show: Performance loss is mainly reflected in the first

③Using different
       v-ifs in scenarios: used to switch infrequent scenarios

     ​ v-show: Used for frequently switching scenes.

④ Difference in security
     v-if: good security (if the dom element is not displayed, it cannot be seen in elements at all)

     ​ v-show: Bad security. (If the dom element is not displayed, it can still be seen in elements, then, those who understand the program can modify it)

3. Why is it not recommended to use v-for and v-if together?

①Reason:

     The priority of v-for is higher than that of v-if. If the data that meets the conditions is relatively small (original data), it will cause a lot of performance waste

②Solution:

In computed, first filter out the data that meets the conditions. Then, v-for directly loops through the filtered data. Computed is cached, so when the original data does not change, the data will not be filtered multiple times, thus improving efficiency

//所以可以采取以下做法,先判断v-if
<div id="app">
    <ul v-if="flag">
        <li v-for="(item,index) in arr">{
   
   {index}}---{
   
   {item}}</li>
    </ul>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            flag: true,
            arr: ['h', 'e', 'l', 'l', 'o']
        }
    })
</script>

Day02

1. Two-way binding principle

1. Two-way: M---->V V---->M

2. It is completed by using events and attributes.

3. v-model is a syntactic sugar. The essence is the combination of events and attributes.

      1), for text boxes (single-line and multi-line): value attribute and input event. If you add the modifier lazy. The event becomes a change event.

      2), for radio: the checked attribute and change event used, and the value attribute needs to be added to the radio

      3), for checkbox: the checked attribute and change event used

             3.1), if the application is in multiple selection, you need to add the value attribute to the checkbox

             3.2), if the application is in single selection, no need to add

      4), for select: use value attribute and change event

The essence of v-model used on radio

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    </style>
</head>
<body>
    <div id="app">
        性别:
        <input type="radio"  v-bind:checked="sex=='女'"  @change="changeSex" value="女" >女
        <input type="radio"  v-bind:checked="sex=='男'" @change="changeSex" value="男" >男
        <hr/>
        性别:
        <input type="radio"  v-model="sex" value="女" >女
        <input type="radio"  v-model="sex" value="男">男
        <p>已选择的性别:{
   
   {sex}}</p>
    </div>
</body>
</html>
<script src="./js/vue2.js"></script>
<script>
    let vm = new Vue({
        el: "#app",
        data: {
            sex:"女"
        },
        methods: {
          changeSex(e){
            this.sex = e.target.value;
          }
        }
    });
</script>

The essence of v-model used on checkbox

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        爱好:
        <input type="checkbox" :checked="hobbys.includes('篮球')" @change="changeHobby" value="篮球">篮球
        <input type="checkbox" :checked="hobbys.includes('足球')" @change="changeHobby" value="足球">足球
        <input type="checkbox" :checked="hobbys.includes('乒乓球')" @change="changeHobby" value="乒乓球">乒乓球
        <hr />
        <input type="checkbox" v-model="hobbys" value="篮球">篮球
        <input type="checkbox" v-model="hobbys" value="足球">足球
        <input type="checkbox" v-model="hobbys" value="乒乓球">乒乓球
        <p>爱好:{
   
   {hobbys}}</p>
    </div>
</body>
</html>
<script src="./js/vue2.js"></script>
<script>
    let vm = new Vue({
        el: "#app",
        data: {
            hobbys: ['足球']
        },
        methods: {
            changeHobby(e) {
                //    if(this.hobbys.includes(e.target.value)){
                //       this.hobbys = this.hobbys.filter(item=>item!=e.target.value);
                //    }else{
                //       this.hobbys.push(e.target.value);
                //    }
                let idx = this.hobbys.indexOf(e.target.value);
                if (idx == -1) {
                    this.hobbys.push(e.target.value);
                } else {
                    this.hobbys.splice(idx, 1);
                }
            }
        }
    });
</script>

v-model used on checkbox (single checkbox) 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <input type="checkbox" :checked="isRead" @change="changeRead">已阅读协议;
        <hr />
        <input type="checkbox" v-model="isRead">已阅读协议;
        <p>阅读协议:{
   
   {isRead}}</p>
        <hr />
        <input type="checkbox" :checked="isRead2=='yes'" @change="changeRead2" true-value="yes" false-value="no">已阅读协议;
        <input type="checkbox" v-model="isRead2" true-value="yes" false-value="no">已阅读协议;
        <p>阅读协议:{
   
   {isRead2}}</p>
    </div>
</body>
</html>
<script src="./js/vue2.js"></script>
<script>
    let vm = new Vue({
        el: "#app",
        data: {
            isRead: false,
            isRead2: "no",
        },
        methods: {
            changeRead() {
                this.isRead = !this.isRead;
            },
            changeRead2(e) {
                // this.isRead2 = (this.isRead2=='yes'?'no':'yes')
                this.isRead2 = (this.isRead2 == e.target.getAttribute("true-value") ? e.target.getAttribute("false-value") : e.target.getAttribute("true-value"))
            }
        }
    });
</script>

Day03

1. The difference between computed and watch

① Similarity: Both can monitor data

② Differences:

    1), concept:

     computed: It is a computed attribute, dependent on other attribute values, and the value of computed is cached. When the value of the dependent attribute changes, the value of computed will be recalculated. The default is read-only (equivalent to the getter function), and it can also Set up getter and setter functions to perform reading and writing.

     watch: It is more of an observation function. Whenever the monitored data changes, a callback will be executed for subsequent operations. It can only set the getter. Watch only monitors one layer by default. If you want to monitor deeply, set the deep property to true.

    2), function:

     computed: It is used for display, which reduces the complexity of the code on the template.

     watch: The detection of attribute changes (equivalent to events), when the value of the attribute changes, the function can be called.

    3) Dependent template call:

     computed: Can only be used on templates.

     watch: cannot be used on templates.

    4), whether asynchronous:

     computed: There can be no asynchronous, only synchronous.

     watch: can be asynchronous.

2. What is virtual dom

The so-called virtual dom, which is what we often call virtual nodes, simulates nodes in DOM through the Object object of IS, and then evolves them into real DOM nodes through specific render (rendering) methods.

3. How to realize in-depth monitoring

First, create a new html project and introduce vue into the project

After introducing wue, define a listening object in the project

After the monitoring object is defined, use the watch method to monitor the entire object

④Finally , after the monitoring event is set, add a deep attribute to the event and set it to true to realize deep monitoring

(Define the listening object first, use the watch method to monitor the entire object, add a deep attribute to the event, and set it to true to achieve deep monitoring)

Fourth, how to understand the filter

Filters are used specifically for data format conversion. Such as: text formatting

① Define command

    1), global definition: Vue.filter ("filter name", filter function (raw data,))

    2), local definition: write in the filters configuration item in the Vue object

②Use instructions:

Used on the template, use the pipe character. The original data is bowed in front of the pipe symbol, and the call of the filter (that is, the call of the function) is followed by the pipe symbol

Application scenarios of filters: Usually in development, there are many application scenarios of filters, such as unit conversion, text formatting, time

formatting etc.

5. What is the understanding of this?

① What is it?

this is the built-in object of the function. this is a synonym. Who this represents depends on the scene (context). In js, the function is the scene of this. Therefore, this generally appears inside the function (in fact, this essence is the scope).

② Several situations of this (static description) The functions mentioned in the following situations are non-arrow functions.

   1) When the function where this is located is an event processing function, this represents the event source.

   2) When the function where this is located is a constructor, this represents the new object.

   3) When the function of this is an instance (object) method, this represents the object calling the method.

   4) When the function where this is located is a globally declared function,

         4.1) In non-strict mode: this means window. (In fact, this point is the same as the third point). Because global functions are methods of the window object

         4.2), in strict mode: this is undefined.

   5), this is in the script tag, which means window.

③ For the real this, you need to look at the call (you only need to know it deeply, and you don’t need to answer this during the interview).

   1), call, apply, bind can change the point of this.

   2), the so-called constructor, I can also call it without new.

   3), the so-called global function, I can also assign it to the event attribute.

④The arrow function does not have this.

That is: when judging the direction of this, don't treat the arrow function as a function.

I don’t tell ordinary people: Arrow functions are lexical analysis domains in the principle of compilation.

Day04

1. How do you understand virtual DOM and diff algorithm

The so-called virtual dom, which is what we often call virtual nodes, simulates the nodes in the DOM through the JS Object object, and then renders them into real DOM nodes through a specific render (rendering) method

①What is virtual dom and diff algorithm:

Virtual DOM: Real dom simulated with JSON objects to improve performance (reduce redraw reflow)

diff algorithm: used to compare the differences between two virtual doms.

②Steps (ideas, process)

   2.1), generate two virtual DOM trees: newVDom, oldVDom.

   2.2), oldVDom and real DOM are consistent

   2.3), when the data changes, it affects (operates) newVDom

   2.4) After operating newVDom, compare the difference between newVDom and oldVDom through the diff algorithm, and mark which nodes to delete and which nodes to add in oldVDom, modify

   2.5) Operate the real DOM according to oldVDom to keep the real Dom consistent with oldVDom

③Explanation of the diff algorithm:

Step by step analyze the node of newVdom, find its position in oldVdom, if found, move to the next DOM element, if not found, it means a new node, then create a new node to insert. After the traversal is completed, if there are nodes in oldVdom, it means that these nodes have been deleted in newVdom, just delete them.

Two, one-way data flow

Parent -----> child data transfer is possible. Not the other way around.

Prop (short for property) is one-way binding: when the property (data) of the parent component changes, it will be transmitted to the child component, but not vice versa. This is to prevent child components from inadvertently modifying the state of the parent component, so as to avoid the data flow of the application from becoming difficult to understand. ​ In addition, every time the parent component is updated, all props of the child component will be updated to the latest values. This means you should not change props inside child components. If you do this, Vue will warn you in the console.

Summarize:

Components are tags, and props are attributes of tags.

prop is the data passed in from the outside, and data is the data inside the component.

3. data is a function, why is the data of the vue component a function

​The data option of a component must be a function, and it must return an object (that is, the data of the vue object). Only in this way, each instance (vue component object) can maintain an independent copy of the returned object, otherwise, When components are reused, data affects each other. That is: the scope of components (should) be independent.

​Simple answer: If it is not a function, then the data of the multiplexed components share the same memory space.

Day06

1. Communication between components:

① Parent-child component passing value

    1), father ---> child pass: props, ref

    ref: reference, the subcomponent object can be found through ref. ref is the same as obtaining dom in native (such as: getElementById). A piece of text is required: custom tags are tags, and getting dom in js is getting tags. Components are dom objects

    this.$refs.sonRef;// equivalent to document.getElementById("sonId");

    Through this.$refs.sonRef, the dom object is obtained, which is equivalent to obtaining the subcomponent object.

    this.$refs.sonRef is equivalent to this in the subcomponent [this sentence must be understood]

 

    2), son ---> father pass: emit

② Brother components

    1), child 1 ---> father ---> child 2

    2), event bus (event-bus)

Principle: use the $on and $emit of the vue object to complete.

Specific method: Suppose SonA transmits data to SonB. Create a new empty vue object. Introduce the vue object in SonA and SonB.

$emit: trigger event (in SonA)

$on : bind event (in SonB)

Two, readyState and status in ajax

①What does readyState mean:

readyState: It indicates the status of the request and response process (which step has been reached).

0: Not initialized, [XMLHttpRequest object created]

1: Initialization, [call open completed]

2: The backend receives the request,

3: The backend is processing

4: The backend responds back.

② What does status mean:

status: Indicates the description of the response result

200: (Success) The server has successfully processed the request This means that the server served the requested web page.

400: (Bad Request) The server did not understand the syntax of the request

401: (Unauthorized) The request requires authentication.

403: (Forbidden) The server rejected the request

404: (Not Found) The server could not find the requested page

408: (Request Timed Out) The server timed out while waiting for the request

500: (Server Internal Error) The server encountered an error and could not complete the request

502: (Bad Gateway) The server is acting as a gateway or proxy and received an invalid response from an upstream server

503: (Service Unavailable) The server is currently unavailable (due to overloading or down for maintenance). Usually, this is only a temporary state

504: (Gateway Timeout) The server is acting as a gateway or proxy, but did not receive the request from the upstream server in time

505: (HTTP Version Unsupported) The server does not support the HTTP protocol version used in the request

3. Prototype and prototype chain

① Prototype:

    1), each constructor (class) will have a prototype attribute (prototype).

    2), the purpose of the prototype attribute:

Let all instances share properties and methods , and what is shared is the properties and methods on the prototype property (prototype) of the constructor (class). Thus, memory is saved. The instance finds the prototype property of the constructor (class) through __proto__the property .

    3) There is also a constructor attribute in the prototype attribute, which points to the constructor (class) itself.

②Prototype chain:

When using an object to access a property or method, first look for it in the memory of the object itself, if not found, go to the __proto__memory (prototype of the class) pointed to by (prototype) to find, if not found, then in the prototype of the class __proto__(the prototype of the parent class) search, and so on, always find the Object, if not found, it will display an error (such as: is not defined, or is not a function, etc.).

This kind of search along __proto__the is the search of the prototype chain. That is the meaning of the prototype chain.

Day07

1. Understanding of MVC, MVP, MVVM

All three are project architecture patterns (not class design patterns), that is, if the structure of a project is layered, different layers are responsible for different responsibilities.

①MVC:

The emergence of MVC is used in the back end (full stack era)

M: model, model:

It mainly completes business functions . In database-related projects, the addition, deletion, modification and query of the database belong to the model (emphasis). (db folder in nodeJS), no pages, pure logic

V: view, view:

Mainly responsible for data display (HTML+CSS, dynamic web pages (jsp, php files containing html)) page display and user interaction.

C: controller, controller:

Mainly responsible for the core process of each business , reflected in routing and middleware in the project (routes folder in nodeJS)

②MVP

MVP is to change the C in MVC to P. The main limitation is that M and V cannot communicate directly (call each other, transfer data). Communication between M and V must go through P.

P: Presenter, presenter

It is mainly used to connect the M layer and V layer, complete the interaction between the Model layer and the View layer, and can also process business logic.

③MVVM:

MVVM is to change P in MVP to VM. It mainly reflects the two-way binding between MVs . View changes can be synchronized in Model, and vice versa. Vue is an MVVM framework. To be precise, when using the Vue framework to complete the project, the MVVM pattern is used.

VM:ViewModel

It mainly completes the data communication of MV, and it is two-way binding. The synchronization between View and Model is completely automatic without human intervention, so developers only need to pay attention to business logic, do not need to manually operate DOM, and do not need to pay attention to the synchronization of data status. Complex data status maintenance is completely done by MVVM for unified management.

Two, vue2, vue3 (component object) life cycle [fourth difference]

①What is the life cycle

The life cycle of a Vue object (component) is a series of processes from creation, mounting, rendering, updating, to destruction. It is the life cycle.

②The life cycle of vue2 has four stages and eight hook functions

The first stage: the data mount stage. The data mounting phase is to mount the attributes of the data configuration item to the Vue object itself. and do hijack

                      There is a hook function before and after: beforeCreate, created

The second stage: template rendering stage: render (display) the data on the template.

                      There is a hook function before and after: beforeMount, mounted

The third stage: template update stage: when the data (data used on the template) changes, the new data will be rendered to the template.

                      There is a hook function before and after: beforeUpdate, updated

view 2:

The fourth stage: component destruction: there is a hook function before and after: beforeDestroy and destroyed

view 3:

The fourth stage: component destruction: [only this is different from vue2]

                     There is a hook function before and after: beforeUnmount and unmounted

Day08

One, keep-alive

keep-alive can cache components and their status (data), avoiding the performance loss caused by frequent creation and destruction of components.

It has three properties:

Used for caching components, generally used in conjunction with routing and dynamic components.

②Provide include and exclude attributes. Both support characters or regular expressions. include means that only components with matching names will be cached, and exclude means that any components with matching names will not be cached. The priority of exclude is higher than that of include. The values ​​of these two props are
both It can be a character string separated by English characters, a regular expression, or an array containing these two types: it will be matched according to the name option of the component, so if the component wants to break the Keeplive level storage conditionally , you must explicitly declare a name option.
middle

③Corresponding to the two hook functions activated and deactivated, when the component is activated, the hook function activated is triggered, and when the component is removed, the hook function deactivated is triggered.

2. What is the execution order of Vue's parent component and child component lifecycle hook functions?

The execution order of Vue's parent-child component hook function can be classified into 4 parts:

Part 1: First Load Render

father beforeCreate -> father created > father beforeMount -> child beforeCreate -> child created > child

beforeMount -> 子mounted -> 父mounted.

Part 2: When the parent component modifies the props value of the child component

father beforeUpdate -> child beforeUpdate -> child updated -> father updated

Part 3: When the data modified by the parent component has no relationship with the child component

Will not affect the component parent beforeUpdate -> parent updated

Part IV: Destruction Process

beforeDestroy -> child beforeDestroy -> child destroyed -> father destroyed

Day09

 1. Axios interceptor

①What is the axios interceptor?

    Interceptors are callback functions that are called before the front-end and back-end interactions (request and response) reach each other. All requests will call this callback function

② Interceptors are divided into:

    Request interceptor: the callback function called before the request reaches the backend
    Response interceptor: the callback function called before the response reaches the front end

③Problems solved by the interceptor:

    1) Request interceptor: It can handle all public services of requests (before reaching the backend), such as: carrying tokens, displaying loading, adding verification to request bodies, setting request headers, etc. Do different types of processing for different request types, etc.
    2) Response interceptor: It can handle public services of all responses (then or catch arriving at the front end), such as: unified data processing, response error status code, loading hiding, etc.

Day10

1. The difference between $router and $route

$router is the vue-router object, which is the created vue-router object. This object has routing-related APIs, such as: push( ),

replace ( ) go(), back(), forward()

$route is the matched routing object. When the path in the address bar changes, a routing configuration will be matched. Then, the vue-router object will generate a $route object on the component to save the relevant information of the matched route, including: passed parameters, routing meta information, etc. (such as: path, params, query, etc.)

2. The difference between the two routing modes

Differences in appearance: 1), hash has # 2), history has no #

②The difference in principle:

   1), hash uses anchor connection. The location.href and window.hashchange events are used behind the scenes. Anchor connections have their own history.

   2), history.pushState is used behind the history to record the history of the page.

③Differences related to the backend:

   1), hash has nothing to do with the backend

   2), history has a relationship with the backend. When the address bar changes, the browser will send a request to the server by default (resources html, css, js, api interface on the server, pages rendered by the backend, etc.), so when the current backend is not separated: you need to ensure The front-end path and the back-end api or the page rendered by the back-end should not have the same name. In addition, the front-end and back-end are separated, and the front-end server needs to configure a 404 page to return index.html.

3. Routing parameters

vue-router has two ways of passing parameters: params and query.

params

First, you need to use dynamic routing matching {path: "/path/: parameter name", name: "routing name"} in the routing configuration

1), pass (transfer when jumping, the programming method is the same as the statement)

//声明式:
1)、字符串写法
<router-link to="/路径/参数的值"></router-link>
//编程式:
this.$router.push("/user /01001");
2、对象写法
<router-link :to="{name:路由名,params:{参数名:参数值}}"></router-link>
//编程
this.$router.push({ name: user', params: { id:  01001' }})

2), connected to [internal reception of routing components]

this,$route.params,参数名

queny

1), pass

//声明式
//1)、字符串写法:
<router-link to=路径?参数名1=参数值&参数名2=参数值2”></router-link>
//2) 对象写法:
<router-link :to="{path路径?参数名1=参数值&参数名2=参数价2}}"></router-link>
//编程式
                   同上

2), connect

this.$route.query.参数名

Day11

1. Routing lazy loading (on-demand loading)

①Why use

Reduce server pressure, speed up page rendering, object instantiation in the getter method, perform their duties, and reduce coupling.

② what is

Lazy loading is actually delayed loading, that is, to load related objects when the object needs to be used

③Solution

  • vue asynchronous component

  • import() of es

  • webpack的require.ensure()

2. Route Guard

①What is a routing guard

Control the jump of the component, and restrict whether it can enter the corresponding component of a certain path. Determine whether a component can be accessed based on business logic.

② What are the classifications of routing guards?

   1), global guard

          1.1), pre-hook: beforeEach

          1.2), post hook: afterEach

    2), route exclusive guard

           2.1), only pre: beforeEnter

    3), component internal guards

           3.1), Pre: beforeRouteEnter

           3.2), route update, component reuse: beforeRouteUpdate

           3.3), leave: beforeRouteLeave

③Parameters of routing hook function:

to: the route to jump to (routing object information) target

from: the source of the route (routing object information) from where to jump

next: The function body must require next() to allow the route to jump and switch normally, next(false) stays in place, next("forced modification to another route path"

Day12

1. vuex

①What is vuex

Vuex is a state (data) management tool that can complete data sharing between components (communication of components)

②The role of vuex

    1), vuex can save global data (data warehouse) for the entire application

    2) The data saved by vuex is responsive

    3) The data saved by vuex can track state changes

③Vuex (core concept) configuration items:

    1), state: data warehouse, which stores all shared data , which is equivalent to the data in the vue component

    2), Getters: Data derived , equivalent to computed in vue components

    3), Mutations: When modifying the state data, use mutation, which is related to the tracking state and can only have synchronous code

    4), Action: Solve the problem that there can only be synchronous code in the mutation, and there can be asynchronous code in the action

    5), modules: modular

④Vuex data flow

The vue component dispatches (dispatch) action . Submit ( commit) the mutation in the action , modify (mutate) the data of the state in the mutation, and after the number of the state is modified, it will be rendered responsively to the template.

⑤How to use modularization

    1) When the project is relatively large, all global data is stored in the state, which will be very confusing, what should I do? Use module to process data in different categories, namely: modularization. Each module is an independent store. Then import all sub-module stores from the overall store.

    2), how to solve the duplicate name of (getters, mutations, actions)

             2.1)、namespaced:true

             2.2) When using getters, mutations, and actions in the module, the module name needs to be added in front of it:

Format:

模块名/getters或者mutations或者actions的名字

⑥Auxiliary function:

mapState, mapGetters,mapMutations, mapActions

   1), function:

Simplified code: no need to use $store in components.

   2), specific use:

mapState, mapGetters will be mapped to the computed of the component

mapMutations, mapActions will be mapped to the methods of the component.

Day13

The realization principle of $nextTick:

①Why use Vue.nextTick()

First, JS is single threaded, so, how does it handle asynchronous operations.

All synchronization tasks are executed on the main thread, forming an execution stack.

Outside the main thread, there will be a task queue. As long as the asynchronous task has a result, an event will be placed in the task queue (so, also called the event queue) and queued (in a waiting state).

When all synchronous tasks in the execution stack are executed, the tasks (events) in the task queue (event queue) will be read. That is: the tasks in the task queue end the waiting state and enter the execution stack.

The main thread keeps repeating the third step. Until the code in the task queue and execution stack is executed.

Understand an event loop: javascript event loop (event loop) - jiang7701037's blog - CSDN blog

Secondly , vue updates the idea of ​​DOM. The asynchronous update queue is used, so the event loop is used. The purpose is to improve performance and avoid unnecessary repeated DOM updates. That is: after the data is updated in vue, the DOM will not be updated immediately, but the DOM update caused by the data will be put into the asynchronous update queue. Wait for the next event loop (tick), and render the UI between two ticks. In this way, the programmer cannot immediately obtain the updated DOM after changing the data, and does not know when the DOM can be updated. Based on this, vue provides the nextTick function. The programmer puts the code for manipulating the updated DOM into the callback function of nextTick. Callback function called by nextTick after updating DOM. Sample code:

this.msg = "hello"
this.$nextTick(()=>{
     操作更新后DOM的代码。
});

②What is Vue.nextTick()

The code idea of ​​Vue.nextTick

function nextTick(cb){
    //DOM 更新
    cb();
}

So, how does vue know that the DOM is updated?

MutationObserver: This is a new API for HTML5. An interface for monitoring DOM changes, which can monitor child node deletion, attribute modification, text content modification, etc. that occur on a DOM object

In addition, considering that micro-tasks are less time-consuming than macro-tasks, browser compatibility. Therefore, the priority of delayed calls in vue is as follows: Promise > MutationObserver > setImmediate > setTimeout

③Application scenario:

Answer: When you need to operate "the (new) dom affected by the data update", use $nextTick(). Moreover, $nextTick() must be called immediately after the data is updated;

​ To put it another way: when the dom needs to be manipulated, and the dom is the dom that is re-rendered after the data is updated (modified).

You can think of it this way, $nextTick(cb); is updated, updated caused by a certain data, not updated caused by all data

Understanding of SPA

①The concept of single page application

SPA: single page application, single page application.

That is, there is only one html page (file) in the whole project . When loading for the first time, all html, css, and js are all loaded. Page switching is completed by deleting and creating (adding) the dom.

②Advantages and disadvantages of single page application

advantage:

    1) The single-page application has less pressure than the server. [Because: for the first time, or as long as HTML, CSS and JS are loaded, switching pages does not need to go to the server to request HTML, CSS and JS]

    2) Partial refresh, so the user experience is good. [By deleting, adding, and modifying DOM]

   3) Separation of front and rear ends

    4), the page effect will be more cool (such as the transition animation when switching page content)

shortcoming:

    1), not conducive to SEO (Search Engine Optimization). Such as: Baidu, 360 and other search engines included.

    2) It takes a lot of time to load for the first time (it can be solved by lazy loading of routes)

    3) Navigation is not available. If you must navigate, you need to realize forward and backward by yourself (vue-router is ready). The complexity of the page has increased a lot

    4) It is easy to cause CSS naming conflicts. [Use scoped or BEM to solve it]

Guess you like

Origin blog.csdn.net/weixin_72756818/article/details/130206692