fromVue interview questions are often asked in the interview

Look at the interview questions just to fill in the gaps and see what you don’t know. Remember, don’t think that if you memorize the interview questions, everything will be ok. It’s better to understand the principles behind it, so that you can talk with confidence during the interview. Otherwise, a slightly skilled interviewer will be able to see if there is genuine talent or just memorize the interview question. (These are some basic VUE interview questions, don’t waste your time reading down)

I. Understanding of MVVM?

MVVM stands for model-view-ViewModel. The Model represents the data Model, where you can also define the business logic for data modification and manipulation. View represents the UI component that transforms the data model into a UI for presentation. A ViewModel listens for changes in Model data, controls the behavior of the View, and handles user interactions. In MVVM architecture, there is no direct connection between View and Model, but interaction through ViewModel. The interaction between Model and ViewModel is bidirectional, so the changes of View data are synchronized to Model. Changes to Model data are immediately reflected in the View. The ViewModel connects the View layer with the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need to focus on business logic, do not need to manually manipulate DOM, do not need to pay attention to the synchronization of data state. Complex data state maintenance is managed entirely by MVVM.

Ii. Vue’s life cycle

beforeCreateData observation and initialization events have not yet startedcreatedComplete data observation, property and method operations, initialization events,Called after the el is replaced and mounted to the instance. The example is configured to replace the DOM object pointed to by the EL attribute with the HTML compiled above. Finish rendering the HTML from the template to the HTML page. Ajax interactions occur during this process.beforeUpdateCalled before data is updated and occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering additional rerendering.updatedCalled after the virtual DOM has been re-rendered and patched due to data changes. When called, the component DOM is already updated, so DOM-dependent operations can be performed. In most cases, however, you should avoid changing the state during this period, as this can lead to an infinite update loop. This hook is not called during server-side rendering.beforeDestroy(pre-destruction) called before instance destruction. The instance is still fully available.destroyed(After destruction) called after the instance is destroyed. When called, all event listeners are removed and all subinstances are destroyed. This hook is not called during server-side rendering. 1. What is the VUE lifecycle? A: The lifecycle of a Vue instance is the process from creation to destruction. The life cycle of a Vue is a series of processes from the beginning of creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and destroying.

2. What is the role of the VUE lifecycle? A: It has multiple event hooks throughout its lifecycle, making it easier to form good logic when controlling the process of the entire Vue instance.

3. How many phases are there in the VUE life cycle? A: It can be divided into 8 stages altogether: before/after creation, before/after loading, before/after update, and before/after destruction.

4. Which hooks trigger the first page load? A: Generates beforeCreate, created, beforeMount, mounted.

5. In which cycle is DOM rendering completed? A: DOM rendering is done in Mounted.

3. Vue implements the principle of two-way data binding: Object.defineProperty ()

Vue implements bidirectional data binding mainly by using data hijacking combined with publiser-subscriber mode, hijacking setter and getter of each attribute through ** object.defineProperty () **, publishing messages to subscribers when data changes, and triggering corresponding listening callback. When passing an ordinary Javascript Object to a Vue instance as its data option, Vue iterates through its properties, turning them into getters/setters with Object.defineProperty. Getters/setters are invisible to the user, but internally they let Vue track dependencies and notify changes when properties are accessed and modified.

The two-way data binding of VUE takes MVVM as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor the data changes of its model, and uses Compile to parse and Compile template instructions (vUE is used to parse {{}}). Finally, watcher is used to build a communication bridge between observer and Compile to achieve data change – > view update; View Interactive Changes (INPUT) — > Data Model changes the bidirectional binding effect.

Js to achieve a simple two-way binding

<body><divid="app"><inputtype="text"id="txt"><pid="show"></p></div></body><scripttype="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>
Copy the code

4. Parameter transfer between Vue components

Parent component to child component: the child component accepts data through the props method. The $emit method is used to send parameters from the parent component to the child component. 2. The parent component sends the value eventBus from the child component to the parent component. This is suitable for small projects. (Although many people recommend using VUEX directly, depending on the demand. Technology is only the means, the end is king.

Vue routing implementation: Hash mode and history mode

** Hash mode: ** in the browser symbol “#”, # and # after the character called hash, window.location.hash; Features: Hash is in the URL, but is not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages. In hash mode, only the content before the hash symbol is included in the request, such as www.xxx.com. Therefore, the back end will not return a 404 error even if the route is not fully covered.

** History mode: ** History uses new HTML5 features; Two new methods are provided: pushState (), replaceState () to modify the browser history stack, and popState events to listen for state changes. In history mode, the URL of the front end must be the same as the URL of the back end, for example, www.xxx.com/items/id. The back end will return a 404 error if there is no routing for /items/ ID. Vue-router’s official website states: “However, this mode needs to be configured in the background to play well… So, you add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, it should return the same index.html page that your app depends on.”

Vue is different from Angular and React.

The following distinction may not be correct as the version is constantly being updated. I only use VUE in my work and am not familiar with Angular and React. Similarities with AngularJS differences: Both support directives: built-in directives and custom directives; Both support filters: built-in filters and custom filters; Both support bidirectional data binding; None of them support low-end browsers.

Differences: AngularJS is expensive to learn, such as adding Dependency Injection, while vue.js provides simple and intuitive apis. In terms of performance, AngularJS relies on data being dirty checked, so the more Watcher you have, the slower it is; Vue.js uses dependency tracing based observations and uses asynchronous queue updates, where all data is triggered independently.

React uses a special JSX syntax, and Vue. Js is also recommended for component development. Vue has a special file format, and has some conventions for file contents. The central idea is the same: everything is a component, and component instances can be nested; Both provide reasonable hook functions that developers can customize to handle requirements; Do not build AJAX, Route and other functions into the core package, but in the way of plug-in loading; The feature of mixins is supported in component development. React uses the Virtual DOM to do dirty checks on rendered results. Vue.js provides instructions and filters in the template, which can be very convenient and fast to operate Virtual DOM.

Vue route hook function

The home page can control navigation jump, beforeEach, afterEach, etc., generally used for page title modification. Some require login to adjust the page’s redirection function.

BeforeEach has 3 main parameters to, from, and next:

To: route The destination route object to be entered.

From: route Indicates the route that the current navigation is about to leave

Next: function must call the method resolve hook. The execution depends on the call parameters of the next method. You can control the jump of web pages.

What is VUex? How to use it? Which functional scenarios use it?

Reading-only states are concentrated in stores; The way to change that is to submit mutations, which is a simultaneous thing; Asynchronous logic should be encapsulated in actions. Import store and inject in main.js. Create a new directory store… . Export. The scenarios include: status between components, music playing, login status, and adding to shopping cart in a one-page application

state
mutations
getters
action

Solution: {count: 0},mutations: {increment(state) {state.count++}},actions: { increment(context) {context.commit('increment')}}})Copy the code

When the modules project is particularly complex, each module can have its own state, mutation, action, and getters, which makes the structure very clear and easy to manage.

constmoduleA = {state: { ... },mutations: { ... },actions: { ... },getters: { ... }}constmoduleB = {state: { ... },mutations: { ... },actions: { ... }}conststore = new Vuex.Store({modules: {a: moduleA,b: moduleB})
Copy the code

Vue – CLI How to add custom commands?

1. Create local directives

Var app = new Vue({el: '#app', data: {}, // Create directive (multiple) directives: {// Dir1: {inserted(el) {// The first argument in the instruction is domconsole.log (el), which is currently being used for the instruction; console.log(arguments); El.style. width = '200px'; el.style.height = '200px'; el.style.background = '#000'; }}}})Copy the code

2. Global instructions

Vue.directive('dir2', { inserted(el) { console.log(el); }})Copy the code

3. Use of instructions

<divid="app"><divv-dir1></div><divv-dir2></div></div>
Copy the code

How does VUE customize a filter?

HTML code:

<divid="app"><inputtype="text"v-model="msg" />
     {{msg| capitalize }}
</div>
Copy the code

JS code:

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

Globally defined filter

Vue.filter('capitalize', function (value) { if (! value) return''value = value.toString() returnvalue.charAt(0).toUpperCase() + value.slice(1) })Copy the code

The filter accepts the value of the expression (MSG) as its first argument. Capitalize filter will receive the value of MSG as the first parameter.

11. What do you know about Keep-alive?

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering. After vue version 2.1.0, keep-alive added two new attributes: include(cache of included components) and exclude(exclude components are not cached and have a higher priority than include).

Method of use

<keep-aliveinclude='include_components'exclude='exclude_components'><component><! -- Whether the component is cached depends on include and exclude attributes --></component></keep-alive>Copy the code

Parameter Description Include-string or regular expression. Only components with matching names will be cached. Exclude-string or regular expression components with matching names will not be cached. Both can use commas to separate strings, regular expressions, and arrays. Remember to use V-bind when using re’s or arrays.

Use the sample

<! -- Comma-separated strings, only components A and B are cached. --><keep-aliveinclude="a,b"><component></component></keep-alive><! - regular expressions (need to use the v - bind, in line with the matching rules will be cached) - > < keep alive: - include = "/ a | b/" > < component > < / component > < / keep alive - > <! --><keep-alive:include="['a', 'b']"><component></component></keep-alive>Copy the code

12. Interview questions you can answer in one sentence

1. CSS only applies to the current component

2. The difference between v-if and v-show answer: v-if is rendered according to the condition, v-show is the block or none of display;

3.The difference between the routerA:Router is a “router instance” object that contains route jump methods, hook functions, and so on.

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

5. Vue several common instructions answer: V-for, V-if, V-bind, V-ON, V-show, V-else

6. What are the common modifiers of vue? .prevent: Submit events that no longer reload the page; . Stop: prevents the click event from bubbling. .self: Fires when an event occurs in the element itself rather than a child element; .capture: event listening, called when an event occurs

7. Can V-ON bind multiple methods? A: you can

8. What is the function of the key value in vUE? A: When vue.js is updating a rendered element list with V-for, it defaults to a “reuse in place” 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 will simply reuse each element here and make sure it shows every element that has been rendered under a specific index. The key’s main purpose is to update the virtual DOM efficiently.

9. What are the calculated attributes of vUE? A: Putting too much logic into a template can make the template too heavy and difficult to maintain, so try to compute attributes in cases where complex processing of data is required and may be used multiple times. Benefits: (1) the data processing structure is clear; (2) Rely on data, data update, processing results automatically update; ③ Inside the attribute this points to the VM instance; (4) When template is called, write the calculation attribute name directly. ⑤ Commonly used is getter method, get data, can also use the set method to change the data; (6) Compared with methods, methods recalculates regardless of the dependent data. However, when the dependent data does not change, computed data is obtained from the cache and does not recalculate.

10. Single-page applications such as VUE and their pros and cons A: Pros: VUE aims to implement data binding of responses and composite view components through as simple an API as possible, with a responsive data binding system at its core. MVVM, data-driven, componentized, lightweight, simple, efficient, fast, module-friendly. Disadvantages: Does not support earlier versions of browsers, as low as IE9; Not conducive to SEO optimization (if you want to support SEO, it is recommended to render components through the server); The first time to load the home page is relatively long; You can’t use the browser’s navigation buttons. You need to move forward and backward.

PS: The missing case code will be added in a few days. Some of the description may not be clear enough, if there is ambiguity, I may have misunderstood.