Vue interview, often asked questions/vue knowledge Point collation

Source: Internet
Author: User

Look at the interview questions, just to check the gaps, to see their own aspects still do not understand. Remember not to think that the back of the test, it is all right, it is best to understand the principle behind, so that the interview can be talked about. Otherwise, a little bit of the level of the interviewer can see, whether there is true knowledge or just back in the face of the question. (All of the basic Vue interview questions, the great God doesn't have to waste time looking down)

First, what is the understanding of MVVM?

MVVM is an abbreviation for Model-view-viewmodel.
model represents the data model, and the business logic for data modification and manipulation can also be defined in model.
View represents the UI component, which is responsible for transforming the data model into a UI presentation.
ViewModel Monitoring model data changes and control the view behavior, processing user interaction, simple understanding is a synchronous view and model of the object, connect model and view.
In the MVVM architecture, there is no direct connection between the view and the model, but through ViewModel interaction, the interaction between model and ViewModel is bidirectional, so the view data changes are synchronized to the model, and the model Changes in the data are also immediately reflected in the view.
The ViewModel connects the view layer to the model layer through two-way data binding, and the synchronization between the view and model is completely automatic, without human intervention, so the developer only has to focus on the business logic and does not need to manipulate the DOM manually. There is no need to focus on the synchronization of data states, and complex data state maintenance is managed entirely by MVVM.


Second, the life cycle of Vue

beforecreate(before creation) the data observation and initialization events have not yet started
created(after creation) complete data observations, properties and methods of operations, initialization events, $el attributes are not shown yet
Beforemount(before loading) is called before the mount starts, and the associated render function is called for the first time. The instance has completed the following configuration: Compile the template, and generate HTML for the data and templates in it. Note that the HTML is not mounted on the page at this time.
mounted(after loading) the newly created VM in El. $el replaced and mounted to the instance after it is called. The instance has completed the following configuration: Replace the DOM object pointed to by the El attribute with the HTML content compiled above. Complete the HTML rendering in the template to the HTML page. Ajax interactions are performed during this process.
BeforeUpdate(before the update) is called before the data is updated, before the virtual Dom is re-rendered and patched. You can change the state further in the hook without triggering an additional re-rendering process.
updated(after update) is called after the virtual Dom is re-rendered and patched due to data changes. When called, the component Dom has been updated, so you can perform operations that depend on the DOM. In most cases, however, you should avoid changing the state during this period, as this may result in an infinite loop being updated. The hook is not called during server-side rendering.
Beforedestroy(before destruction) is called before the instance is destroyed. The instance is still fully available.
destroyed(after destruction) is called after the instance is destroyed. Once called, all event listeners are removed and all child instances are destroyed. The hook is not called during server-side rendering.
1. What is the Vue life cycle?
A: The process of creating a Vue instance from creation to destruction is the life cycle. From the beginning to create, initialize data, compile templates, Mount dom→ rendering, update → Render, destroy, and so on a series of processes called Vue life cycle.


What is the role of the 2.vue life cycle?
A: There are multiple event hooks in its life cycle, which makes it easier to form good logic when controlling the entire Vue instance process.


How many phases does the 3.vue life cycle have in total?
A: It can be divided into 8 stages: pre/post, before/after the update, before/after the destruction.


4. How many hooks will be triggered by the first page load?
A: This will trigger the following several beforecreate, created, beforemount, mounted.


In which cycle has the 5.DOM rendering been completed?
A: DOM rendering has been completed in mounted.


Three, Vue implementation of data two-way binding principle: Object.defineproperty ()

Vue implements data two-way binding is mainly: mining data hijacking combined with the Publisher-subscriber mode , through object.defineproperty () to hijack the various attributes of the Setter,getter, Post a message to the subscriber when the data changes, triggering the corresponding listener callback. When a plain Javascript object is passed to the Vue instance as its data option, Vue iterates over its properties and uses Object.defineproperty to convert them to getter/setter. Users don't see Getter/setter, but internally they let Vue track dependencies and notify changes when properties are accessed and modified.


Vue's data bidirectional binding uses MVVM as the gateway to data binding, integrating Observer,compile and watcher, listening to the data changes of their model through observer, and parsing the compiled template instructions through compile (Vue is used to parse { {}}), eventually using watcher to build a communication bridge between observer and compile to update the view with data changes; View interaction change (input), data model changes the two-way binding effect.


JS for simple two-way binding

<body>    <div id="app">    <input type="text" id="txt">    <p id="show"></p></div></body><script type="text/javascript">    var obj = {}    Object.defineProperty(obj, ‘txt‘, {        get: function () {            return obj        },        set: function (newValue) {            document.getElementById(‘txt‘).value = newValue            document.getElementById(‘show‘).innerHTML = newValue        }    })    document.addEventListener(‘keyup‘, function (e) {        obj.txt = e.target.value    })</script>
Iv. parameter passing between Vue components

1. The parent component and the child component pass value
Parent component to Child component: Sub-component accepts data by props method;
Child components passed to Parent component: $emit method passing parameters
2. Data transfer between non-parent and child components, sibling component transfer value
Eventbus is the creation of an event hub, which is equivalent to a broker that can be used to pass events and receive events. Project comparison hours, with this more appropriate. (Although a lot of people recommend direct use of Vuex, specifically to see the demand.) Technology is only a means, the purpose is to be benevolent. )

Five. Vue's routing implementation: hash mode and history mode

Hash Mode: in the browser symbol "#", #以及 # after the character is called a hash, read with Window.location.hash;
Features: Hash although in the URL, but not included in the HTTP request, to guide the browser action, the server is not safe and useless, hash does not reload the page.

History Mode:The new feature of HTML5 is used in history, and two new methods are provided: Pushstate (), replacestate () can make modifications to the browser Chronicle stack, and popstate the event's audible state change.

What is the difference between Vue and angular and react?

(The version is constantly updated, the following differences may not be correct.) I only use Vue in my work, not very familiar with angular and react.
1. The difference from Angularjs
Same point:
Both support directives: built-in directives and custom directives, both support filters: Built-in filters and custom filters, both support bidirectional data binding, and do not support low-end browsers.

Different points:
Angularjs high learning costs, such as increased dependency injection characteristics, and vue.js itself provides a simple and intuitive API, in performance, Angularjs rely on data dirty check, so watcher more slow ; Vue.js uses a dependency-tracking-based observation and uses an asynchronous queue update, and all data is triggered independently.

2. The difference from react
Same point:
React uses a special JSX syntax, Vue.js in component development is also respected in writing. Vue Special file format, there are some conventions on the contents of the file, both need to be compiled after use; The central idea is the same: everything is a component, the components can be nested between instances, all provide a reasonable hook function, you can allow developers to customize to deal with the requirements; no built-in columns Ajax,route Can be loaded into the core package, but in the form of plug-ins, supporting Mixins features in component development.
Different points:
The virtual DOM used by react will perform dirty checks on the rendered results, and Vue.js provides instructions, filters, etc. in the template, which can be easily and quickly manipulated by the virtual DOM.

Vii. hook function for Vue routing

Homepage can control navigation jump, Beforeeach,aftereach, etc., generally used for page title modification. Some need to log in to adjust the page redirection feature.

Beforeeach has 3 main parameters To,from,next:

to: The destination route object to which the route will enter,

from: Route current navigation is going to leave the routing

Next: function must call this method resolve this hook. The execution effect relies on the invocation parameters of the next method. You can control the page jumps.

Viii. What is Vuex? How to use? Which feature scenario uses it?

The state that is used only for reading is placed in the store; the way to change state is to commit mutations, which is a synchronous thing; asynchronous logic should be encapsulated in the action.
Introduced in the Main.js store, injected. Create a new directory store, ..... Export.
Scenarios are: In a single page app, the status between components, music playback, login status, add to Cart

State
Vuex uses a single state tree, where each app will contain only one store instance, but a single state tree and modularity do not conflict. Data stored in the state, you can not directly modify the data inside.
Mutations
Mutations defines a method that dynamically modifies the state or data in the Vuex store.
Getters
A computed property similar to Vue, used primarily to filter some data.
Action
Actions can be understood as the asynchronous manipulation of data by turning the method of data inside the mutations into an asynchronous processing method. The view layer distributes the action through Store.dispath.

const store = new Vuex.Store({ //store实例      state: {         count: 0             },      mutations: {                         increment (state) {          state.count++         }          },      actions: {          increment (context) {          context.commit(‘increment‘)   } }})

Modules
When the project is particularly complex, it allows each module to have its own state, mutation, action, and getters, making the structure very clear and easy to manage.

const moduleA = {  state: { ... },  mutations: { ... },  actions: { ... },  getters: { ... } }const moduleB = {  state: { ... },  mutations: { ... },  actions: { ... } }const store = new Vuex.Store({  modules: {    a: moduleA,    b: moduleB})
Ix. vue-cli How to add a custom directive?

1. Create a local directive

var app = new Vue({    el: ‘#app‘,    data: {        },    // 创建指令(可以多个)    directives: {        // 指令名称        dir1: {            inserted(el) {                // 指令中第一个参数是当前使用指令的DOM                console.log(el);                console.log(arguments);                // 对DOM进行操作                el.style.width = ‘200px‘;                el.style.height = ‘200px‘;                el.style.background = ‘#000‘;            }        }    }})

2. Global Directives

Vue.directive(‘dir2‘, {    inserted(el) {        console.log(el);    }})

3. Use of instructions

<div id="app">    <div v-dir1></div>    <div v-dir2></div></div>
X. How does vue customize a filter?

HTML code:

<div id="app">     <input type="text" v-model="msg" />     {{msg| capitalize }}</div>

JS Code:

var vm=new Vue({    el:"#app",    data:{        msg:‘‘    },    filters: {      capitalize: function (value) {        if (!value) return ‘‘        value = value.toString()        return value.charAt(0).toUpperCase() + value.slice(1)      }    }})

Global definition Filters

Vue.filter(‘capitalize‘, function (value) {  if (!value) return ‘‘  value = value.toString()  return value.charAt(0).toUpperCase() + value.slice(1)})

The filter receives the value of an expression (msg) as the first parameter. The capitalize filter will receive the MSG value as the first parameter.

Xi. the understanding of keep-alive?

keep-alive is a built-in component of Vue that allows the contained components to remain in state or to avoid re-rendering.
After Vue 2.1.0, Keep-alive added two properties: include (contained component cache) and exclude (excluded components are not cached, priority is greater than include).

How to use

<keep-alive include=‘include_components‘ exclude=‘exclude_components‘>  <component>    <!-- 该组件是否缓存取决于include和exclude属性 -->  </component></keep-alive>

Parameter interpretation
Include-string or regular expression, only components with name matching will be cached
Exclude-a string or regular expression in which any component with a name match is not cached
The Include and exclude properties allow components to be conditionally cached. Both can use "," to separate strings, regular expressions, and arrays. When using regular or array, remember to use V-bind.

Using the example

<!-- 逗号分隔字符串,只有组件a与b被缓存。 --><keep-alive include="a,b">  <component></component></keep-alive><!-- 正则表达式 (需要使用 v-bind,符合匹配规则的都会被缓存) --><keep-alive :include="/a|b/">  <component></component></keep-alive><!-- Array (需要使用 v-bind,被包含的都会被缓存) --><keep-alive :include="[‘a‘, ‘b‘]">  <component></component></keep-alive>
12, a sentence can answer the question of the face

1.css only works in the current assembly
A: Write scoped in the Style tab for example:

2.v-if and V-show differences
Answer: V-if According to the condition whether renders, V-show is the display block or none;

3. The difference between $route and $router
A: $route is the "Routing information Object", including the routing information parameters such as Path,params,hash,query,fullpath,matched,name. And $router is the "route instance" object includes the route jump method, the hook function and so on.

What are the two cores of 4.vue.js?
Answer: Data-driven, component systems

5.vue of several commonly used directives
Answer: V-for, V-if, V-bind, v-on, V-show, V-else

6.vue commonly used modifiers?
A. Prevent: The submit event no longer overloads the page; STOP: block click event bubbling;. Self: Triggers when an event occurs in the element itself, not a child element; Capture: Event listener, when event occurs

7.v-on can I bind more than one method?
Answer: You can

What is the function of the key value in 8.vue?
A: When vue.js is updating a rendered list of elements with v-for, it defaults to the "in-place reuse" policy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but rather simply reuse each element here and make sure that it shows each element that has been rendered under a specific index. Key functions primarily to update the virtual DOM efficiently.

9. What is Vue's computed properties?
A: Putting too much logic into a template can make the template too heavy and difficult to maintain, and as much as possible to calculate the properties when it requires complex processing of the data and possibly multiple uses. Benefits: ① makes the data processing structure clear; ② relies on data, data updates, processing results are automatically updated; ③ compute attribute internal This points to the VM instance, ④ when the template is called, write the computed property name directly; ⑤ commonly used getter method, get data, You can also use the Set method to change the data; ⑥, regardless of the methods, the methods is recalculated, but the dependent data is not changed and computed is fetched from the cache and is not recalculated.

10.vue and other single page applications and their pros and cons
A: The goal of Vue is to implement the data binding and the combined view component of the response through the simplest possible API, and the core is a responsive data binding system. MVVM, data-driven, modular, lightweight, concise, efficient, fast, module-friendly.
Disadvantage: does not support the low version of the browser, the minimum support to IE9; not conducive to SEO optimization (if you want to support SEO, the recommended service side to render the component); The first time to load the home page takes a relatively long time; you can not use the browser's navigation buttons need to self-implement and backward

PS: Missing case code, these days to fill up. Some places may not be described clearly enough, if there is ambiguity, maybe I understand wrong.

Original address: 1190000016344599

Vue interview, often asked questions/vue knowledge Point collation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.