preface

Vue is the most popular front-end framework in China, almost every interview will involve relevant knowledge points, here according to the previous interview records sorted out, convenient for myself to check the deficiency. If there are any mistakes in this article, please correct them. Thank you.

1. Talk about the principle of Vue’s bidirectional binding data

Vue implements bidirectional data binding mainly by using the mode of data hijacking combined with “publisher – subscriber”, using Object.defineProperty() to hijack the setter and getter of each attribute, release messages to subscribers when data changes, and trigger corresponding listening callback.

2. What is the difference between one-way data flow and two-way data binding

One-way data flow: As the name implies, data flow is one-way. The direction of data flow can be tracked, and the flow is single, which makes it faster to track down problems. The downside is that it’s not very convenient to write. To make the UI change, various actions must be created to maintain the corresponding state.

Two-way data binding: Data is interlinked, hiding the operation of data changes within the framework. The advantage is that it simplifies a lot of non-business code in a scenario where forms interact a lot. The disadvantage is that local state changes cannot be traced, which increases the difficulty of debugging when errors occur.

3. Vue-router removes “#” from URL

Vue-router uses hash mode by default, so when the route is loaded, the URL in the project will have a “#”. If you don’t want to use “#”, you can use another mode of vue-router history:

new Router({
    mode: 'history'.routes: [...]. })Copy the code

It should be noted that when we enable the history mode, because our project is a single-page application, there will be a “404” when the route jumps, which cannot access the static resource. At this time, the server needs to add a candidate resource that covers all cases: If the URL does not match any static resources, the same “index.html” page should be returned.

4. Understanding of MVC and MVVM

MVC

Features:

  1. ViewSend instructions toController;
  2. ControllerAfter completing the business logic, requestModelTo change state;
  3. ModelSend the new data toViewUsers get feedback.

All communication is one-way.

MVVM

Features:

  1. Communication between the parts is two-way;
  2. Bidirectional binding is adopted:ViewChanges are automatically reflected inViewModelAnd vice versa.

Features:

  1. Communication between the parts is two-way;
  2. Bidirectional binding is adopted:ViewChanges are automatically reflected inViewModelAnd vice versa.

5. Understanding of Vue life cycle

A Vue instance has a full life cycle, which is the process from creation to destruction of an instance.

  • beforeCreate(): Executed between instance creation, data is not loaded.
  • created(): can initialize data after instance creation, data loading, and before DOM rendering.
  • beforeMount()The virtual DOM is created and the data is changed for the last time before rendering.
  • mounted(): The page and data are rendered and the real DOM is mounted.
  • beforeUpadate(): Rerender before triggering.
  • updated(): The data has been changed and the DOM has been re-render, so the data changes will fall into an infinite loop.
  • beforeDestory() 和 destoryed(): The former is executed before destruction (the instance is still fully available) and the latter is executed after destruction.

6. Component communication

The parent component communicates with the child component

The sub component uses the props property to bind the data of the parent component for communication.

The child component communicates with the parent component

Emit the parent component’s event in the child component via $emit.

Data transfer between non-parent and sibling components

/* Create a new Vue instance as an intermediate carrier */
let event = new Vue();

/* Listen on events */
event.$on('eventName'.(val) = > {
    / /... do something
});

/* Triggers the event */
event.$emit('eventName'.'this is a message.');
Copy the code

7. Difference between V-if and V-show

When v-if is used, the page will not have the HTML tag generated if the value is false.

V-show shows that HTML elements exist regardless of whether the value is true or false, except for display in the CSS.

8. What is the difference between route and router

$router is an instance of VueRouter. If you want to navigate to different urls, use the $router.push method.

$route indicates the current router jump object, which can obtain name, path, query, and params.

What is nextTick

$nextTick is a deferred callback performed after the next DOM update cycle, and when you use $nextTick after modifying the data, you can retrieve the updated DOM in the callback.

10. Why must the Vue component data be a function

Because of the features of JS itself, if data is an object, then because the object itself belongs to the reference type, when we modify one of the attributes, it will affect the data of all Vue instances. If data is returned as an object as a function, the data attributes of each instance are independent and do not affect each other.

11. What is the difference between computed attributes and event methods

We can define the same function as a method or as a calculated property. For the end result, both approaches are the same.

Difference:

  • computedComputed properties are cached based on their dependencies and reevaluated only if their associated dependencies change.
  • method: As soon as rerendering occurs,methodThe call always executes the function.

12. How is Vue different from jQuery

JQuery focuses on the view layer by manipulating DOM to achieve some logical rendering of the page. Vue focuses on the data layer and reduces DOM manipulation through two-way binding of data, which ultimately manifests itself at the DOM level.

Vue uses the idea of componentalization, which makes the responsibility of project subset clear, improves the development efficiency, and facilitates the reuse and collaborative development.

13. How to customize instructions in Vue

Global registration

// Register a global custom directive 'V-focus'
Vue.directive('focus'.// When the bound element is inserted into the DOM...
    inserted: function (el) {
        // Focus elements
        el.focus()
    }
})
Copy the code

Local registration

directives: {
    focus: {
        // The definition of a directive
        inserted: function (el) {
            el.focus()
        }
    }
}
Copy the code

14. How to customize filters in Vue

You can register a custom filter with the global method vue.filter (), which takes two parameters: the filter ID and the filter function. The filter function takes a value and returns the converted value.

Vue.filter('reverse'.function (value) {
    return value.split(' ').reverse().join(' ')})Copy the code
<! -- 'abc' => 'cba' -->
<span v-text="message | reverse"></span>
Copy the code

Filters also accept global and local registrations.

15. Understanding of Keep-alive

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering.

<keep-alive>
    <component>
        <! This component will be cached! -->
    </component>
</keep-alive>
Copy the code

You can use the PROPS provided by the API to implement dynamic caching of components.

16. The role of key in Vue

The special attribute of key is mainly used in the virtual DOM algorithm of Vue to identify VNodes when comparing old and new nodes. If keys are not used, Vue uses an algorithm that minimizes dynamic elements and tries to repair/reuse the same type of elements as much as possible. With a key, it rearranges elements based on the change in the key and removes elements where the key does not exist.

Child elements that have the same parent must have a unique key. Duplicate keys cause render errors.

17. Advantages and disadvantages of single-page applications such as Vue

advantages

  • Good interactive experience
  • Good front and rear end working separation mode
  • Reduce server stress

disadvantages

  • SEO is difficult
  • Forward and backward management
  • The initial loading takes much time