1. What are the defects of Object.defineProperty in Vue’s responsivity principle? Why is Proxy adopted in Vue3.0 and Object. DefineProperty abandoned?
Object. DefineProperty cannot monitor array subscript changes, resulting in adding elements by array subscript and cannot respond in real time. Object.defineproperty can only hijack attributes of an Object, which requires traversal of each Object, each attribute, and deep traversal if the attribute value is an Object. A Proxy can hijack an entire object and return a new object. Proxy can Proxy not only objects, but also arrays. You can also proxy dynamically added properties.Copy the code
What is the sequence of parent and child Vue lifecycle hooks
Load render process parent beforeCreate-> Parent created-> Parent beforeMount-> child beforeCreate-> child created-> child beforeMount-> Child Mounted -> Parent Mounted Child Component update process Parent beforeUpda Te -> Child beforeUpdate-> Child updated-> Parent Updated Parent Component Update Process Parent beforeUpdate-> Parent updated Destroy Process Parent beforeDestroy-> Child beforeDestroy-> Child Destroyed -> Parent Dest royedCopy the code
3. Talk about your understanding of VUex
When the interviewer asks us what vuex is about, we should not just say “Vuex is a state management model developed for vuue.js application”, and try not to let the interviewer continuously ask (always ask yourself that you don’t know and then say that you are not enough to take a salary cut), we should explain it from three aspects at once:
1. What is vuex?
2. Core concepts of VUEX;
- Vuex attributes;
- Vuex data transfer process;
3. Why vuex?
For question 1, we can follow the description on the official website. Vuex is a state management pattern developed specifically for vuue.js applications (it uses centralized storage to manage the state of all components of the application and rules to ensure that the state changes in a predictable manner).
For question 2, vuEX has five core attributes: State, getter, mutation, Action and Module
- State: Indicates the state of data storage. After the store is registered in the root instance, the
this.$store.state
To access; Corresponding to data in VUE; The vUE component reads data from the Store. If the data changes, the component will update accordingly. - Getter: can be thought of as a computed property of the store. Its return value is cached based on its dependencies and is recalculated only if its dependencies change.
- Mutation: The only way to change the state in Vuex’s store is to commit mutation.
- Action: Contains any asynchronous operation that changes the state indirectly by submitting mutation.
- Module: Splits the store into modules, each with state, mutation, action, getters, and even nested submodules.
The data transfer process of VUEX is as follows:
We need to invoke Dispatch to trigger methods in actions when a component makes data changes. Every method in Actions has a commit method, and when the method is executed, commit triggers the mutations method to modify the data. Every function in mutations will have a state parameter, so that the data of state can be modified in mutations, and when the data is modified, it will be transmitted to the page. The data on the page also changes.
As for the third problem, the method of parameter passing will be very tedious for multi-layer nested components, and it cannot do anything about state passing between sibling components. We often use parent-child components to reference multiple copies of state directly or through events to change and synchronize. These patterns are very fragile and often result in unmaintainable code. So we need to extract the shared state of the components and manage it in a global singleton. In this mode, our tree of components forms a giant “view” where any component can get state or trigger behavior no matter where it is in the tree! In addition, by defining and isolating concepts in state management and enforcing compliance with certain rules, our code becomes more structured and maintainable.
4. Vue realizes the principle of two-way data binding
Vue implements data bidirectional binding mainly by using data hijacking combined with published-subscriber mode. Through Object.defineProperty(), the setter and getter of each attribute is hijacked to publish messages to subscribers when data changes and trigger corresponding listening callback. When passing an ordinary javascript Object to a Vue instance as its data option, Vue iterates over its properties, converting them to getters/setters with Object.defineProperty. The user does not see getters/settters, but internally Vue tracks dependencies and notifies 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, listens to the data changes of its model through Observer, and interprets and compiles template instructions through compile. Finally use Watcher to build a communication bridge between observer and compile, to achieve data changes — “view update; View interaction changes model Changes the effect of bidirectional binding.
5. 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 change of View data will be synchronized to Model, and the change of Model data will be immediately reflected on View. ViewModel connects View layer and Model layer through two-way data binding, and the synchronization between View and Model is completely automatic, without interference, so developers only need to pay attention to 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 complete.
6, virtual DOM implementation principle?
The realization principle of virtual DOM mainly includes the following three parts: ① Use JavaScript objects to simulate the real DOM tree and abstract the real DOM; ② Diff algorithm — Compare the difference between two virtual DOM trees; ③ Pach algorithm — The difference between two virtual DOM objects is applied to the real DOM tree.
7. Vue project optimization
1. Optimization at the code level V-IF and V-Show distinguish between use scenarios And avoid simultaneously using v-if long list performance optimization event destruction image resource lazy load route lazy load third-party plug-in on demand optimization infinite list performance server render SSR or pre-render
2. Optimization of Webpack level Webpack compresses images to reduce ES6 to ES5 redundant code extraction common code template precompilation extraction component CSS optimization SourceMap build results output analysis Vue project compilation optimization
3. Optimization of basic Web technologies Enable gzip compression browser cache CDN use Chrome Performance to find Performance bottlenecks
8. How does Vue monitor array changes
Principle: 1, the use of function hijacking, rewrite the array method
2. Vue rewrites the prototype chain of the array in Data, pointing to the array prototype method defined by itself, so that when the array API is called, it can notify the dependency update, and if the array contains reference types, the reference types in the array will be monitored again.
The main methods to override arrays: push, POP, Shift, unshift, splice, sort, reverse
9. Why does Vue use asynchronous rendering?
Vue will update the view asynchronously again after the latest data update for performance reasons, since it does not use asynchronous updates and each update will re-render the current component
Principle: Dep.notify () notifies watcher of the update operation, calls watcher’s update in turn, puts the watcher to the queue, and asynchronously empts the Watcher queue
10. How does nextTick work?
The nextTick method uses macro tasks and micro tasks, and defines an asynchronous method. Multiple calls to nextTick will queue the method, and the current queue will be cleared by this asynchronous method. So this nextTick method is an asynchronous method
The principle of
NextTick (CB) Call nextTick to pass cb
Callbacks.push (cb) stores the callback function into an array
TimerFunc () call timerFunc – 1, try to use promises callback |
– 2, try to use MutationObserver callback flushcallbacks | =”
– 3, try to use setImmediate callback | nextTick execution
– 4, and end use setTimeout callback | incoming method
Return to the promise
MVC and MVVM architectural patterns
MVC: interaction from the front end to the back end. The front end request finds the corresponding controller and gets the data through the route. Data exchange is one-way. Simply speaking, the front end is responsible for the page and the back end is responsible for the data
MVVM: Refines the front-end of MVC, with data hanging directly onto the framework for rendering updates. The increasing demand for front-end data makes it an inevitable trend, and MVVM can be said to be a separation from the FRONT-END part of MVC
12. Compilation principle of templates in Vue
Compilation principle
1. How does vUE go from component to page? How to go from component code to a render function?
- The template is converted into an AST tree (virtual Dom object, VNode tree), where the regular implementation parses the code and then extracts the relevant data into the object tree
- Optimization of tree
- Generate JS code from the AST tree
Render and update
How do components render to the real DOM
- Generate a virtual Dom object from our component object using the CreateElement method
- Taking the virtual DOM, Vue builds the child component’s constructor using the vue.extend() method, where we finish the virtual DOM manipulation and instantiate it
- When the update method is executed, we first create the CreateCompontent method to create a virtual DOM object that we pass in. After instantiation, Vue will render the component’s internal Watcher. The whole is a rendering process
Therefore, the internal update relies on the diff algorithm of the core process of Patchvnode for comparison and then updates the interface
Vue uses asynchronous rendering
1. Why asynchronous rendering
If the changed value corresponds to the same Watcher, we have to update it twice according to the synchronization process
So our actual process is going to be
Refresh the screen when the data changes notify notify to update the view, and then we will store the corresponding Watcher with an ID tag in a queue, so we can clean up the same watcher and keep only the latest one, and render the page. Finally, the nextTick method is called to asynchronously empty the stored watcher queue and render the next component
14. Vuex principle
Vuex implements a one-way data flow, with data stored globally in a state. When a component wants to change data in the state, it must do so through Mutation, which also provides a subscriber pattern for external plug-in calls to obtain updates of state data. However, when all asynchronous operations or batch synchronization operations need Action, the state cannot be directly modified by the Action. The data of the state must be modified through Mutation, and finally rendered to the view according to the change of the state.
How do YOU listen for changes inside an object in VUE
Method 1: Deep listen on the whole OBJ
watch:{
obj:{
handler(newValue,oldValue){
console.log('obj changed');
},
deep:true.// Depth traversalImmediate:true
// By default, the watch listener is not triggered for the first binding. If the value is true, the watch listener can be executed for the first binding}},Copy the code