1. Under what circumstances should I use Vuex?
- If the application is simple enough, it is best not to use Vuex,A simplestoreMode
- When you need to build a medium and large single-page application, useVuexCan better manage state outside of the component
2. What is the difference between Vuex and pure global objects?
- VuexThe state storage is responsive. whenVueComponent fromstoreWhen reading the status, ifstoreIf the status in the system changes, the corresponding components will be updated efficiently accordingly.
- Cannot be changed directly storeIn the state. changestoreThe only way to state in is to explicitly commit(commit) mutation. This allows us to easily track the changes of each state, so that we can implement some tools to help us better understand our applications.
3. Why can't asynchronous operation be done in the mutation of Vuex?
- VuexThe only way for all status updates inmutation, The asynchronous operation is passedActionTo submitmutationRealization, so that we can easily track the changes of each state, so that we can implement some tools to help us better understand our applications.
- EachmutationAfter the execution is completed, it will correspond to a new state change, sodevtoolsYou can take a snapshot and save it, and then you can achieve ittime-travelUp. in casemutationSupporting asynchronous operation, there is no way to know when the state is updated, and the state cannot be tracked well, which brings difficulties to debugging.
4. Does vuex's action have a return value? What is returned?
- store.dispatchCan handle triggeredactionThe processing function returnsPromise,andstore.dispatchStill returnPromise
- ActionUsually asynchronous, you have to knowactionWhen will it end or combine multipleactionTo handle more complex asynchronous processes, you can defineactionWhen returning apromiseObject, you can distributeactionCan be returned by processingPromiseHandling asynchronous processes
Onestore.dispatchMultiple triggers in different modulesactionfunction. In this case, only when all trigger functions are completed, the returnedPromiseWill be executed.
5. What is the difference between computed and watch and used scenarios?
computed: Is a calculated attribute, depends on the value of other attributes, andcomputedThe value of is cached, only the attribute value it depends on changes, the next time it is obtainedcomputedWill be recalculated when the value ofcomputedThe value of
watch: There is no caching, and it is more of an "observation" function. It is similar to the monitoring callback of some data. When the monitored data changes, the callback will be executed for subsequent operations; when we need to monitor the properties of the object in depth, we can turn ondeep: trueOption, so that every item in the object will be monitored
- When we need to perform numerical calculations and rely on other data, we should use computed, Because you can usecomputedThe caching feature of to avoid recalculation every time the value is obtained;
- When we need to perform asynchronous or expensive operations when the data changes, we should usewatch,usewatchOptions allow us to perform asynchronous operations (access to an API), limit how often we perform the operation, and set intermediate states before we get the final result. These are things that calculated properties cannot do.
- When we need to perform numerical calculations and rely on other data, we should use
6. What are the communication methods of Vue2.x components?
Parent-child component communication
- Event mechanism (**parent->child props, child->parent $on, $emit)
- Get parent-child component instance $parent, $children
- Ref calls the properties or methods of the component by obtaining the instance
- Provide, inject (not recommended, very commonly used in component libraries)
Brother component communication
Vue.prototype.$bus = new Vue
-Vuex -eventBus This method uses an empty Vue instance as the central event bus (event center), which can be used to trigger events and monitor events, so as to achieve communication between any components, including parent-child, intergenerational, and sibling components Copy code
Cross-level component communication
- $attrs, $listeners
- Provide, inject
7. Why v-for and v-if are not recommended to be used together
- when v-forwithv-ifAt the same node,v-forPriority ratiov-ifHigher, which meansv-ifWill be repeated separately for eachv-forIn the loop. If the array to be traversed is very large, and the data to be displayed is very small, this will cause a lot of performance waste
- Recommended for this scenario computedTo filter the data first
8. Why is the data in the component a function?
- If a component is reused multiple times, multiple instances will be created. Essentially, these instances all use the same constructor.
- in casedataIf it is an object, the object belongs to a reference type, which will affect all instances. So in order to ensure that the components of different instancesdataDo not conflict,dataMust be a function.
9. Why can't the child component modify the Prop passed by the parent component?/How to understand the one-way data flow of vue?
- VueAdvocate one-way data flow, that is, the updates of the parent props will flow to the child components, but the reverse will not work.
- This is to prevent accidentally changing the state of the parent component, making the data flow of the application difficult to understand.
- If the one-way data flow is destroyed, when the application is complex,debugThe cost will be very high.
10. How does v-model realize two-way binding?
- v-modelIt is used to create two-way binding on form controls or components
- His essence isv-bindwithv-onSyntactic sugar
- Use on a componentv-model, The default binding name for the component isvalueofpropAnd namedinputevent
11. What is the realization principle of nextTick?
- Next time DOMAfter the update cycle is over, the delayed callback is executed, and nextTick is used immediately after the data is modified to obtain the updatedDOM.
- nextTickMainly used macro tasks and micro tasks.
- Try to adopt according to the execution environmentPromise, MutationObserver, setImmediate, Use if none of the abovesetTimeoutDefines an asynchronous method, called multiple timesnextTickThe method will be stored in the queue, and the current queue will be cleared through this asynchronous method.
12. What is the principle of Vue event binding?
- Native event binding is throughaddEventListenerBinding to real elements, component event binding is throughVue custom $onAchieved.
13, talk about the role of virtual Dom and key attributes
Because of the operation in the browserDOMIt is very expensive. Frequent operationDOM, Will produce certain performance problems. This is the reason for the virtual Dom.
Virtual DOMThe essence is to use a native JS object to describe a DOM node. Is trueDOMLayer of abstraction. (That is, in the source codeVNodeClass, it is defined insrc/core/vdom/vnode.jsin. )
The realization principle of virtual DOM mainly includes the following 3 parts:
- diff algorithm-compare the differences between two virtual DOM trees;
- pach algorithm Apply the difference between two virtual DOM objects to the real DOM tree.
key isVueinvnodeThe only mark through thiskey,ourdiffOperation can be more accurate and faster
- More accurate: because the key is not reused in place, in sameNodefunctiona.key === b.keyIn the comparison, in-situ multiplexing can be avoided. So it will be more accurate.
- Faster: Use the uniqueness of the key to generate a map object to obtain the corresponding node, which is faster than the traversal method
- More accurate: because the key is not reused in place, in
14. Why is it not recommended to use index as the key?
- Not recommendedindex as the key, basically the same as if it is not written, Because no matter how the order of your array is reversed, the index is always 0, 1, 2 in this arrangement, causing Vue to reuse the wrong old child nodes and do a lot of extra work
15. Tell me about your understanding of the life cycle of Vue
- beforeCreate: After the instance is initialized, the data observation and event configuration are not ready at this time (undefined)
- created: The value of the data data is read, but the DOM has not been generated yet
- beforeMount: The page has not been successfully rendered into the data in our data
- mounted: Successfully rendered
- beforeUpdate: Before the view is re-rendered and updated
- updated: The view has been updated.
- beforeDestroy: Destroy the current component
- destroyed. After successful destruction, the destroyed hook will be triggered
- keep-aliveHas its own independent hook function activated and deactivated
16. What is the calling sequence of component life cycle in Vue?
- The calling order of the components is first father and then child, and the order of rendering completion is first child and then father.
- The destruction operation of the component is the parent first and then the child, and the order of completion of the destruction is the child first and then the parent.
17. At what stage can I access and manipulate the DOM?
In hook function
18. In which life cycle is your interface request generally placed?
Can be in the hook functioncreated, beforeMount, mountedBecause in these three hook functions, data has been created, the data returned by the server can be assigned.
However, it is recommended to call asynchronous requests in the created hook function, because calling asynchronous requests in the created hook function has the following advantages:
- The server data can be obtained faster, and the page loading time can be reduced;
- ssr does not support beforeMount and mounted hook functions, so putting it in created helps consistency;
19. What are the implementation principles of vue routing hash mode and history mode, and what is the difference between them?
- #The change of the hash value behind will not cause the browser to send a request to the server. If the browser does not send a request, the page will not be refreshed
- By monitoring the hashchange event, you can know what changes have occurred in the hash, and then update part of the content of the page according to the changes in the hash.
- The realization of the history mode is mainly the two APIs published by the HTML5 standard, pushState and replaceState. These two APIs can change the URL, but will not send a request. In this way, you can monitor url changes to update part of the content of the page.
- In url display, hash mode has "#", history mode does not
- When the page is refreshed, the hash mode can be loaded to the page corresponding to the hash value normally, and if the history is not processed, a 404 will be returned. Generally, the backend needs to be configured to redirect all pages to the homepage route.
- Compatibility, hash can support lower version browsers and IE.
20. What are the Vue-router navigation guards?
- Global front/hook:beforeEach, beforeResolve, afterEach
- Guards exclusive to routing:beforeEnter
- The guard in the component:beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave
21. Why not use arrow functions when writing life cycle hooks or other option/properties in a Vue instance?
- The arrow function itself is not defined thisContext.
- When you use arrow functions in Vue programs(=>)Time,thisKeyword disease will not be bound toVueInstance, so an error will be raised. Therefore, it is strongly recommended to use standard function declarations instead.
22. Tell me about your understanding of keep-alive components
keep-aliveIt is a built-in component of Vue, which can keep the state of contained components and avoid re-rendering. It has the following characteristics:
- Generally used in conjunction with routing and dynamic components for caching components;
- provide includewithexcludeAttributes, both support strings or regular expressions,includeIndicates that only components with matching names will be cached,excludeIndicates that any component with a matching name will not be cached, whereexcludePriority ratioincludehigh;
- Corresponding to two hook functions activated and deactivated, When the component is activated, trigger the hook functionactivated, When the component is removed, the hook function is triggereddeactivated.
23. Tell me about your understanding of SSR?
SSR is server-side rendering, that is, the work of Vue rendering tags into HTML on the client side is completed on the server side, and then the html is directly returned to the client side.
Advantages of SSR
- Better SEO
- First screen loading speed is faster
Disadvantages of SSR
- Development conditions will be restricted, server-side rendering only supports two hooks beforeCreate and created
- When we need some external extension libraries, special processing is required, and the server-side rendering application also needs to be in the Node.js runtime environment
- More server load
24. What Vue performance optimizations have you done?
- Try to reduce the data in the data, the data in the data will increase the getter and setter, and the corresponding watcher will be collected
- v-if and v-for cannot be used together
- If you need to use v-for to bind events to each element, use event proxy
- SPA page uses keep-alive cache component
- In more cases, use v-if instead of v-show
- The key is guaranteed to be unique
- Use routing lazy loading, asynchronous components
- Anti-shake, throttling
- Import of third-party modules on demand
- Dynamic loading of long list scrolling to visible area
- Image lazy loading
- Server-side rendering SSR
- Compressed code
- Tree Shaking/Scope Hoisting
- Use cdn to load third-party modules
- Multi-threaded packaging happypack
- splitChunks extract public files
- `sourceMap optimization
- Skeleton screen
- You can also use cache (client-side cache, server-side cache) optimization, server-side open gzip compression, etc.