VUE Interview Questions Summary

Keywords: Javascript Front-end Vue Vue.js Interview

Previous points here: ↓
Summary of VUE interview questions (I)
11. What is the difference between v-if and v-show

Reference answer:

The v-show instruction allows an element to be displayed or hidden by modifying the CSS attribute of its display

The v-if instruction directly destroys and rebuilds the DOM to achieve the effect of displaying and hiding elements

12. vue common modifiers

Reference answer:

Resolution: reference resources

13. Can v-on monitor multiple methods?

Reference answer: Yes.

Resolution:

<input type="text" :value="name" @input="onInput" @focus="onFocus" @blur="onBlur" />

14. Role of key value in Vue

Reference answer:

You need to use the key to make a unique identification for each node. The Diff algorithm can correctly identify this node, find the correct location area and insert a new node
In a word, key is mainly used to update the virtual DOM efficiently

15. vue cli project upgrade

Reference answer:

Run NPM upgrade vue Vue template compiler in the project directory. If there is no accident, it can run and build normally. If there are any problems, delete the node_ The modules folder and rerun npm i. (in short, upgrade vue and vue template compiler plug-ins)

16. How to use event object in Vue event?

Reference answer:

v-on instruction (can be abbreviated as @)
1. Using the form without parentheses, the event object will be automatically passed in as an argument;
2. Using the parenthesized form, we need to explicitly pass in the event object using the $event variable.

Resolution:

1, event object

(1) Event object of the event

You said you were in the front end, so you must know the event. If you know the event, you must know the event object? Various libraries and frameworks deal with event objects. For example, jquery is encapsulated internally. When we develop it, we don't need to pay attention to the partial compatibility of event objects. Typically, if we want to block default events, in chrome and other browsers, we may write a:

event.preventDefault();

In IE, we need to write:

event.returnValue = false;

Thanks to the cross browser implementation of jquery, we only need to write:

event.preventDefault();

Compatible? jquery internal help us out. Similar examples include preventing event bubbling and event binding (addEventListener / attachEvent). Many back ends use $('xxx '). bind(...), which is not our focus today. Let's move on.

(2) event object in vue

We know that compared with jquery, vue's event binding can be more intuitive and convenient. We only need to add a v-on instruction (which can also be abbreviated as @) on the template to complete the effect similar to $('xxx '). bind, without an operation of querying elements using selectors. We know that in jquery, the event object will be passed into the processing function as an argument by default, as follows

$("body").bind("click", function(event) {
    console.log(typeof event); // object
});

The event object is directly obtained here, so the problem is, what about in vue?

<div id="app">
    <button v-on:click="click">click me</button>
</div>
...
var app = new Vue({
    el: '#app',
    methods: {
        click(event) {
            console.log(typeof event);    // object
        }
    }
});

The implementation method here seems to be consistent with jquery, but in fact, vue is much more complex than jquery. jquery officials also make it clear that v-on is not a simple syntax sugar of addEventListener. In jquery, the callback we pass into the bind method can only be a variable of function table type or an anonymous function. When passing it, it cannot be executed (followed by a bunch of parentheses), otherwise it will become taking the return value of this function as an event callback. As we know, the value accepted by the v-on instruction of vue can be in the form of function execution, such as v-on:click = "click(233)". Here, we can pass any parameters that need to be passed, or even no parameters:

<div id="app">
    <button v-on:click="click()">click me</button>
</div>
...
var app = new Vue({
    el: '#app',
    methods: {
        click(event) {
            console.log(typeof event);    // undefined
        }
    }
});

Eh? What about my event object? Why is it missing? Print and see if arguments. length is also 0, indicating that no arguments are passed in at this time. T_T. What should we do if we need to pass both parameters and event objects?

(3) $event

Looking at the vue document, it is not difficult to find that we can solve this problem by passing a special variable $event into the callback:

<div id="app">
    <button v-on:click="click($event, 233)">click me</button>
</div>
...
var app = new Vue({
    el: '#app',
    methods: {
        click(event, val) {
            console.log(typeof event);    // object
        }
    }
});

Well, that looks normal.
To sum up:

Using the form without parentheses, the event object will be automatically passed in as an argument;

Using the parenthesized form, we need to explicitly pass in the event object using the $event variable.

2, Oolong
It's all foreshadowing. Now the real oolong is coming.
Looking through the code of the boy's companion, I came across a code similar to the following:

<div id="app">
    <button v-on:click="click(233)">click me</button>
</div>
...
var app = new Vue({
    el: '#app',
    methods: {
        click(val) {
            console.log(typeof event);    // object
        }
    }
});

When I saw this code, my heart collapsed. After I threw it into chrome, NIMA really could print arguments. length, which is also normal 1. fuck! What the hell is this? Destroy the Three Outlooks?
There are neither passed in arguments nor received formal parameters. The source of this event object is either the superior action chain or... Is the global scope... Overall, I can't help thinking of window. event
. Confirm with MDN again. Sure enough, window. event, ie and chrome all have such an attribute on the window object:

The code was thrown into Firefox to run, and the event turned into undefined. Well, I don't know what to say...

17. Use of $nexttick

Reference answer:

1. What is Vue. nextTick()?

Definition: performs a deferred callback after the end of the next DOM update cycle. Use this method immediately after modifying the data to get the updated dom.

Therefore, the Vue method for obtaining the updated DOM is derived. Therefore, the execution in the Vue. nextTick() callback function should be js code that will operate on the DOM;

Understanding: nextTick() is calling the callback function after the next dom update data. The simple understanding is that when the data is updated and rendered in dom, the function is automatically executed.

<template>
  <div class="hello">
    <div>
      <button id="firstBtn" @click="testClick()" ref="aa">{{testMsg}}</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      testMsg:"Original value",
    }
  },
  methods:{
    testClick:function(){
      let that=this;
      that.testMsg="Modified value";
      console.log(that.$refs.aa.innerText);   //that.$refs.aa get the specified DOM, output: original value
    }
  }
}
</script>

Use this. $nextTick()

methods: {
    testClick: function() {
        let that = this;
        that.testMsg = "Modified value";
        that.$nextTick(function() {
            console.log(that.$refs.aa.innerText); //Output: modified values
        });
    }
}

Note: Vue's implementation of response is not to change the DOM immediately after the data changes, but to update the DOM according to certain policies$ nextTick is a deferred callback executed after the end of the next DOM update cycle. After modifying the data, use $nextTick to get the updated DOM in the callback,

2. When do I need Vue. nextTick()??

1. The DOM operation performed by the created() hook function of Vue life cycle must be placed in the callback function of Vue. nextTick(). The reason is that the DOM is not rendered when the created() hook function is executed, and the DOM operation is futile at this time. Therefore, the js code of DOM operation must be placed in the callback function of Vue. nextTick(). The corresponding is the mounted hook function, because all DOM mounts have been completed when the hook function is executed.

created() {
    let that = this;
    that.$nextTick(function() { //If this.$nextTick() method is not used, an error will be reported
        that.$refs.aa.innerHTML = "created Button content changed in"; //Write to DOM element
    });
}

2. When you want to do something based on the new DOM after changing the data of DOM elements in the project, a series of JS operations on the new DOM need to be put into the callback function of Vue. nextTick(); The popular understanding is: after changing the data, you need to use js when you want to manipulate the new view immediately

<template>
  <div class="hello">
    <h3 id="h">{{testMsg}}</h3>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      testMsg:"Original value",
    }
  },
  methods:{
    changeTxt:function(){
      let that=this;
      that.testMsg="Modified text value";  //vue data change, change dom structure
      let domTxt=document.getElementById('h').innerText;  //Subsequent js operations on dom
      console.log(domTxt);  //It can be seen from the output that the DOM is not updated immediately after vue data modification, and the subsequent DOM is not up-to-date
      if(domTxt==="Original value"){
        console.log("text data After being modified dom Content not updated immediately");
      }else {
        console.log("text data After being modified dom The content was updated immediately");
      }
    },
  }
}
</script>

The correct usage is: after vue changes the dom element structure, use the vue. $nextTick() method to delay the execution of subsequent code after dom data update

    changeTxt: function() {
        let that = this;
        that.testMsg = "Modified text value"; //Modify dom structure

        that.$nextTick(function() { //Use the vue.$nextTick() method to delay execution after dom data updates
            let domTxt = document.getElementById('h').innerText;
            console.log(domTxt); //It can be seen from the output that the DOM is not updated immediately after the vue data is modified,
            if (domTxt === "Original value") {
                console.log("text data After being modified dom Content not updated immediately");
            } else {
                console.log("text data After being modified dom The content was updated immediately");
            }
        });
    }

3. When using a third-party plug-in, if you want to reapply the plug-in when some dom generated by vue changes dynamically, you will also use this method. At this time, you need to execute the method of reapplying the plug-in in in the callback function of $nextTick.

How Vue. nextTick(callback) works:

The reason is that Vue performs DOM updates asynchronously. Once data changes are observed, Vue will open a queue and push the watcher that observes data changes in the same event loop into the queue. If the watcher is triggered multiple times, it will only be pushed to the queue once. This buffering behavior can effectively remove unnecessary calculations and DOM operations caused by duplicate data. At the next event loop, Vue empties the queue and makes the necessary DOM updates.
When you set vm. someData = 'new value', the DOM will not be updated immediately, but only when the asynchronous queue is cleared, that is, when the update is executed at the beginning of the next event cycle. If you want to do something according to the updated DOM state at this time, there will be a problem.. In order to wait for Vue to finish updating the DOM after the data changes, you can use Vue. nextTick(callback) immediately after the data changes. In this way, the callback function will be called after the DOM update is completed.

18. Why must data be a function in Vue components

Reference answer:

In new Vue(), data can be operated as an object. However, in component, data can only exist in the form of a function and cannot be directly assigned to it. This is not designed by Vue itself, but related to the characteristics of JavaScript. Let's review the prototype chain of JavaScript

var Component = function() {};
Component.prototype.data = {
    message: "Love"
};
var component1 = new Component(),
    component2 = new Component();
component1.data.message = "Peace";
console.log(component2.data.message); // Peace

The above two instances refer to the same prototype object. When one instance property changes, the other instance property also changes. Only when the two instances have their own scope, they will not interfere with each other!!!!! This sentence is the key!!!!!

var Component = function() {
    this.data = this.data();
};
Component.prototype.data = function() {
    return {
        message: "Love"
    };
};
var component1 = new Component(),
    component2 = new Component();
component1.data.message = "Peace";
console.log(component2.data.message); // Love

19. Priority of V-for and v-if

Reference answer: v-for takes precedence over v-if

1. v-for is parsed prior to v-if;
2. If it occurs at the same time, each rendering will execute the loop first and then judge the conditions. In any case, the loop is inevitable and wastes performance;
3. To avoid this situation, nest the template in the outer layer, make v-if judgment in this layer, and then make v-for loop inside;
4. If the condition appears inside the loop, those items that do not need to be displayed can be filtered out in advance through the calculation attribute;

20. vue sub component calls parent component's method

Reference answer:

  • The first method is to directly call the method of the parent component through this. $parent. event in the child component
  • The second method is to trigger an event to the parent component with $emit in the child component, and the parent component can listen to this event
  • The third is that the parent component passes the method into the child component and directly calls the method in the child component

Resolution:

The first method is to directly call the method of the parent component through this. $parent. event in the child component

Parent component

<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('test');
      }
    }
  };
</script>

Subcomponents

<template>
    <div>
        <button @click="childMethod()">click</button>
    </div>
</template>
<script>
    export default {
        methods: {
            childMethod() {
                this.$parent.fatherMethod();
            }
        }
    };
</script>

The second method is to trigger an event to the parent component with $emit in the child component, and the parent component can listen to this event

Parent component

<template>
    <div>
        <child @fatherMethod="fatherMethod"></child>
    </div>
</template>
<script>
    import child from "~/components/dam/child";
    export default {
        components: {
            child
        },
        methods: {
            fatherMethod() {
                console.log("test");
            }
        }
    };
</script>

Subcomponents

<template>
    <div>
        <button @click="childMethod()">click</button>
    </div>
</template>
<script>
    export default {
        methods: {
            childMethod() {
                this.$emit("fatherMethod");
            }
        }
    };
</script>

The third is that the parent component passes the method into the child component and directly calls the method in the child component

Parent component

<template>
    <div>
        <child :fatherMethod="fatherMethod"></child>
    </div>
</template>
<script>
    import child from "~/components/dam/child";
    export default {
        components: {
            child
        },
        methods: {
            fatherMethod() {
                console.log("test");
            }
        }
    };
</script>

Subcomponents

<template>
    <div>
        <button @click="childMethod()">click</button>
    </div>
</template>
<script>
    export default {
        props: {
            fatherMethod: {
                type: Function,
                default: null
            }
        },
        methods: {
            childMethod() {
                if (this.fatherMethod) {
                    this.fatherMethod();
                }
            }
        }
    };
</script>

Posted by gofer on Tue, 23 Nov 2021 19:31:19 -0800