Summarized some questions that may be raised in the Vue interview (unfinished)

1. The difference between Vue command v-if and v-show

The same point : they can dynamically control the display or hide of the dom element


1. Difference:


v-if: To control the display or hide of the dom element is to add or delete the entire DOM element;

v-show: To control the display or hide of the DOM is to dynamically add css style display to the DOM element, and set it to block or none. The DOM element still exists.


2. Performance comparison

v-if: has a higher switching cost

v-show: higher initial rendering cost


3. Usage scenarios

v-if: suitable for scenarios where operating conditions are unlikely to change;

When requesting a background interface and using the interface to return data to render multiple elements, the data has no value at first due to the slow network speed. At this time, our page will also render empty data and an error will be reported.
We can use an element as a packaging element and use v-if for conditional judgment. If there is a value, the internal element will be displayed. The final rendering will not include this element, and v-show does not support this.

v-show: suitable for frequent switching

Commodity classification tab, frequent switching;


Two, vue life cycle

1. What is the vue life cycle

The process from creation to destruction of a Vue instance is the life cycle. That is, a series of processes from the beginning of creating, initializing data, compiling templates, mounting Dom→rendering, updating→rendering, uninstalling, etc. We call this the life cycle of Vue.

2. What is the role of the vue life cycle

There are multiple event hooks in its life cycle, which makes it easier for us to form good logic when controlling the process of the entire Vue instance.

3. There are several stages in the vue life cycle

It can be divided into 8 stages in total: before/after creation, before/after loading, before/after update, before/after destruction

4. Which hooks will be triggered on the first page load

The beforeCreate, created, beforeMount, mounted hooks are triggered when the page is loaded for the first time

5. In which cycle DOM rendering has been completed

DOM rendering has been completed in mounted.

6. Briefly describe which fields each period is suitable for?

Some usage methods of life cycle hooks: beforecreate: You can add a loading event here, which is triggered when the instance is loaded. Created: The event when the initialization is completed is written here. If the loading event ends here, asynchronous requests are also suitable to call mounted here: Mount the element and get the DOM node updated: If the data is processed uniformly, write the corresponding function here beforeDestroy: You can make a confirmation box to confirm the stop event. NextTick: Operate the dom immediately after updating the data




Three, Vue's two-way data binding principle

Vue.js uses data hijacking combined with the publisher-subscriber model, hijacking the setter and getter of each property through Object.defineProperty(), publishing messages to subscribers when the data changes, and triggering the corresponding listener callback to render the view .

Specific steps:

The first step: Recursive traversal of the data object of the observer is required, including the properties of the sub-property object, and setter and getter are added
. Assigning a value to this object will trigger the setter, and then you can monitor the data change

The second step: compile parses the template instructions, replaces the variables in the template with data, and then initializes the rendering page view, binds the update function to the node corresponding to each instruction, and adds subscribers who monitor the data. Once the data changes, receive To the notification, update the view

Step 3: Watcher subscribers are the communication bridge between Observer and Compile. The main things they do are:
1. Add themselves to the attribute subscriber (dep) when they are instantiated
2. They must have an update() method.
3. When the property change dep.notice() is notified, it can call its own update() method and trigger the callback bound in Compile, then it will be accomplished.

Step 4: MVVM serves as the entry point for data binding, integrating Observer, Compile and Watcher, monitoring changes in model data through Observer, parsing and compiling template instructions through Compile, and finally using Watcher to set up the connection between Observer and Compile Communication bridge to achieve the two-way binding effect of data change -> view update; view interactive change (input) -> data model change.

What is setter and getter

Objects have two properties:

Data attribute: is the attribute we often use. Accessor
attribute: also known as accessor attribute (accessor attribute is a set of functions to get and set values)

What is Object.defineProperty()?

An object is an unordered collection of multiple name/value pairs. Each attribute in the object corresponds to any type of value.

Define an object in the form of constructor or literal:
Insert picture description here
In addition to the above method of adding properties, you can also use Object.defineProperty to define new properties or modify original properties;

grammar:

Object.defineProperty(obj, prop, descriptor)

parameter:

obj:Required. target;
prop:Required. The name of the attribute to be defined or modified;
descriptor:Required. The characteristics of the target attribute;

return value:

The object passed into the function, that is, the first parameter obj;


Four, vue monitoring and deep monitoring watch

Watch allows us to monitor the change of a value and react accordingly.

    <div id="app">
        用户名:<input type="text" v-model='name'>
        <p>你的名字是:{
    
    {
    
    name}}</p>
    </div>

    <!-- 引入vue -->
    <script src="/node_modules/vue/dist/vue.js"></script>
    <script type="text/javascript">
    
    const app=new Vue({
    
    
        el:'#app',
        data:{
    
    
            name:''
        },
        watch:{
    
      //监控name属性
            name(v1,v2){
    
    
                //v1:当前数入的值
                //v2:上一次输入的值
                console.log(v1,v2)
            }
        }
    })
    </script>

The watch attribute can monitor the change of the name value in the data attribute. When defining the monitoring, the value of name corresponds to a monitoring processing function name().

Bind the name attribute to the dialog box, and bind the name value on the corresponding page, and then test in the browser. The data on the page will change as the value entered in the dialog box changes.

The monitoring processing function name has two parameters:

v1 represents the currently monitored value.
v2 represents the last monitored value.
If you are monitoring an object, you need to perform in-depth monitoring to monitor the changes in the attributes of the object:


    <div id="app">
        用户名:<input type="text" v-model='person.name'>
         <button @click='person.age++'>+</button>
        <p>你的名字是:{
    
    {
    
    person.name}}</p>
        <p>你的年龄是:{
    
    {
    
    person.age}}</p>
    </div>

    <!-- 引入vue -->
    <script src="/node_modules/vue/dist/vue.js"></script>
    <script type="text/javascript">
    
    const app=new Vue({
    
    
        el:'#app',
        data:{
    
    
            person:{
    
    
                name:'',
                age:18
            }
        },
        watch:{
    
      //监控name属性
           person:{
    
    
               deep:true, //开启深度监听
               handler(v){
    
    
                   console.log(v.namge,v.age)
               }
           }
        }
    })
    </script>

Now when defining monitoring, person is an object, and two attributes must be specified:

deep: stands for in-depth monitoring, which not only monitors changes in person, but also changes in attributes of person.
handler: It is the previous monitoring processing function.
Get the specific value in the object through v.name and v.age.


Five, why use key in v-for


1. What is Key

key是给每一个vnode的唯一id,也是diff的一种优化策略,可以根据key,更准确, 更快的找到对应的vnode节点

When we are using v-for, we need to add key to the unit

- 如果不用key,Vue会采用就地复地原则:最小化element的移动,并且会尝试尽最大程度在同适当的地方对相同类型的element,做patch或者reuse。

- 如果使用了key,Vue会根据keys的顺序记录element,曾经拥有了key的element如果不再出现的话,会被直接remove或者destoryed

Guess you like

Origin blog.csdn.net/weixin_53687450/article/details/114786621