1. Vue component communication, one-way data flow of VUE
Communication between Vue components is one of the knowledge points often tested in the interview. This question is similar to the open question. The more methods you answer, of course, the more bonus points, indicating that you are more proficient in Vue. Vue component communication refers only to the following three types of communication: parent-child component communication, intergenerational component communication, and sibling component communication. We will introduce each of these communication modes and explain which types of component communication this method can be applied to.
- Props / $emit is suitable for parent-child component communication
This method is the basis of the Vue component, and I believe most of you have heard of it, so I will not introduce it here with examples.
- Ref and parent/parent /parent /children are used for parent-child component communication
Ref: If used on a normal DOM element, the reference refers to the DOM element; If used on a child component, the reference refers to the component instance parent/parent /parent /children: accessing the parent/child instance
- EventBus (emit/emit /emit/ON) is suitable for parent-child, intergenerational, and sibling communication
This approach uses an empty Vue instance as the central event bus (event hub), which triggers events and listens for events to communicate between any component, including parent, generational, and sibling components.
- Attrs/attrs/attrs/listeners applies to every generation component
Attrs: Contains feature bindings (except class and style) in parent scopes that are not recognized (and retrieved) by prop. When a component does not declare any prop, it contains all bindings in the parent scope (except class and style), and v−bind=”attrs: contains feature bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop. When a component does not declare any prop, it contains all bindings in the parent scope (except class and style), and contains feature bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop by v-bind=”attrs: “. When a component does not declare any prop, all parent-scoped bindings (except class and style) are included, and the internal component can be passed in via v−bind=”attrs”. Often used in conjunction with the inheritAttrs option. Listeners: contain V −on event listeners in the parent scope (native modifiers are not included). Listeners can notice the process by means of V −on=” Listeners: V-ON event listeners in the parent scope (without the.native modifier). The listeners can be listeners of V-on events in the parent scope (native modifiers are not included) via V-on =”listeners: Internal components can be passed on via V − ON =” Listeners”
- Provide/Inject is applicable to inter-generational component communication
The ancestor component provides variables through provider, and the descendant component injects variables through Inject. Provide/Inject API mainly solves the communication problem between cross-level components, but its usage scenario is mainly that sub-components obtain the state of the upper level components, and a relationship between active provision and dependency injection is established between cross-level components.
- Vuex is suitable for parent-child, intergenerational, and sibling component communication
Vuex is a state management mode developed specifically for vue.js applications. At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app.
Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly. The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change.
Vue one-way data flow
- All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes in the state of the parent component from the child, which can make the data flow of your application difficult to understand.
- Additionally, every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console. If a child component wants to modify it, it can only send a custom event through $emit. If the parent component receives the custom event, the parent component can modify it.
- There are two common scenarios for trying to change a prop
- This prop is used to pass an initial value; This child component next wants to use it as a local prop data. In this case, it is best to define a local data property and use the prop as its initial value
- This prop is passed in as a raw value and needs to be converted. In this case, it is best to use the value of the prop to define a calculated property
2, V-model, VUE instruction
In the VUE project, we mainly used v-Model instructions to create two-way data binding on form input, Textarea, SELECT, etc. We knew that v-Model was essentially just syntax sugar. The V-Model internally uses different attributes and throws different events for different input elements: text and Textarea elements use value attributes and input events; Checkbox and radio use the Checked attribute and the change event; The SELECT field takes value as prop and change as an event.
.lazy By default, the V-model synchronizes the value of the input field with the data after each input event (except when the input method combines text as described above). You can change to synchronization using the change event by adding the lazy modifier:
.number If you want to automatically convert user input values to numeric types, you can add the number modifier to the V-model: This is often useful because even when type=”number”, the value of the HTML input element always returns a string. If the value cannot be resolved by parseFloat(), the original value is returned.
The reason why.native plus.native is to convert to native, such as Element +keyup
Note: when using modifiers, order is important; The corresponding code is generated in the same order. Therefore, using V-on :click.prevent. Self blocks all clicks, whereas V-on :click.self. Prevent only blocks clicks on the element itself.
3. Slot and slot-scope
Slot:
- When a component virtual node is created, the virtual node of the component’s son is saved. When the component is initialized, the sons are classified by slot attributes {a:[vNode],b[vnode]}
- Components are rendered with nodes of the corresponding slot properties. (The slot’s scope is the parent component)
slot-scope
- Scope slots are not parsed as child nodes of components. Is parsed into a function that is called to render when the child component renders.
- Normal slots render scoped to the parent component, and scoped slots render scoped to the current child component.
v-slot
- In 2.6.0, we introduced a new uniform syntax (the V-slot directive) for named slots and scoped slots. It replaces slot and slot-scope attributes that have been deprecated but not removed and are still in the document.
4. Life cycle
What is the life cycle?
- A Vue instance has a full life cycle, that is, from the start of creation, initialization of data, compilation of templates, Dom mounting -> render, update -> render, uninstall, etc. We call this the life cycle of a Vue.
When is it called?
- BeforeCreate: called after instance initialization and before data observation
- Created: called after the instance is created. Instance completion: data observation, property and method operations, watch/ Event event callbacks. No $el.
- BeforeMount: Called before mounting, the related render function is called for the first time
- Mounted: Specifies that the vm.$el is mounted to the instance.
- BeforeUpdate: Called before data update, occurs after the virtual DOM is re-rendered and patched, after which the change hook is called.
- Updated: Virtual DOM rerender and patch due to data changes, after which the change hook is called.
- Activited: Exclusive to keep-alive, invoked when the component is activated
- Deactivated: This parameter is exclusive to keep-alive and is invoked when a component is destroyed
- BeforeDestroy: Called before instance destruction, the instance is still available.
- Destroyed: Called after the instance is destroyed. After called, everything indicated by the Vue instance is unbound and all event listeners and all subinstances are removed
What can be done inside each life cycle?
- Created: The instance is already created, and since it is the first created instance, some data and resource requests can be made.
- Mounted: The INSTANCE is mounted. DOM operations can be performed on the instance.
- BeforeUpdate: State can be further changed in this hook without triggering rerendering.
- Updated: It is ok to perform DOM-dependent operations, but avoid changing the state, which may cause an update wireless loop.
- Destroyed: Performs optimization actions, clears timers, and unbinds events.
5, Minxin, filter, custom instruction
Minxin:
- Create a good mixin file and export it.
- Vue file to import
filter
- Call: {{MSG | Mimi (‘ 12 ‘, ‘5’)}}
Custom instruction
- Vue.directive
6, vue.com ponent, vue. The extend
Vue.extend({})
- Extend returns a subclass constructor, the vue instance constructor for default partial options.
vue.component
- Vue.com Ponent is used for global registration components
7, the Computed watch and method
The computed:
- Computed by default is also a Watcher that has a cache, calculating only when the dependent data changes, and reading the cache data when the data does not change. If one data depends on other data, use computed
Watch:
- The function needs to be executed every time. Watch is better suited for asynchronous operations when data changes. If you need to do something when some data changes, use Watch.
Method:
- As long as the method is applied to the template, the view will be re-rendered every time the change is made, which is a high performance overhead
8,template,render,jsx
template
- Syntax is simple, data manipulation is separated from view, and development experience is friendly. However, in some cases, the extension of some functions is limited, such as dynamic use of filters, parsing of string-type template files, and so on. Vue’s render syntax is more low-level than template, allowing javascript syntax to be used in HTML, which greatly extends the power of HTML.
Render function
- The createElement parameter is used to create the desired tag content. There are three parameters: the HTML tag (elementTag), the tag attribute (option), and the children element (children). Create createElement (createElement); render (createElement); render (createElement);
jsx
- JSX is definitely a good choice, but the difference is that JSX can write business code just like we write HTML files, with Babel converting JSX syntax to Render syntax with no side effects.
- JSX does not parse vUE directives, so when template is converted to JSX syntax, each section is written in the same way as the vUE official document
9,data,props
props
- Props (or Properties) is how we pass data down from the parent component to its children.
- Data flows down the tree from the root component, the component at the top. Just like how genes are passed down from generation to generation, parent components pass on their props to their children.
- When we access the props from within the component, we don’t own them, so we can’t change them. But there are situations where we need to change variables, so data comes in handy.
data
- Data is the memory for each component, which is where the data and any other variables you want to track are stored.
10. Application of the name attribute
- When using a component recursive invocation, the component being recursively called must define the name attribute because instead of calling itself from a component registered in components, it uses the name attribute to find the component
- When keep-alive wraps a dynamic component, inactive component instances are cached, and include and exclude attributes are displayed to include or exclude the named component
- Vue-tools plug-in debugging without the name attribute will report an error or warning
11, keep-alive
Keep-alive is a built-in component of Vue that can preserve the state of contained components and avoid re-rendering. It has the following features:
- It is used together with routing and dynamic components to cache components.
- Provide include and exclude attributes. Both of them support strings or regular expressions. Include indicates that only components with matching names will be cached, and exclude indicates that components with matching names will not be cached.
- The hook function activated is activated when a component is activated, and the hook function deactivated is activated when a component is removed.
12. Vue implements animation
- Vue built-in component Transition, elements appear and disappear to animate.
V – enter, v – enter – the to, v – leave, v – leave – the to. V-enter and v-leave-to indicate the start and end states. V-enter-active,v-leave-active indicates the animation process.
- The animate. CSS plug-in
13. The key attribute is used
- The key is a unique token for a Vnode in a Vue. With this key, our diff operation can be more accurate and faster. The DIff process of Vue can be summarized as follows: OldCh and newCh variables each have two end oldStartIndex, oldEndIndex and newStartIndex, newEndIndex, they will be old and new node node pairwise comparison, namely a total of 4 kinds of comparative way: NewStartIndex and oldStartIndex, newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex, If none of the four comparisons match, if the key is set, the comparison will be performed using the key. During the comparison, the traversal will move towards the middle, and the comparison will end once StartIdx > EndIdx indicates that at least one of oldCh and newCh has been traversed.
- Therefore, the function of key in Vue is: Key is the unique mark of Vnode in Vue. Through this key, our diff operation can be more accurate and faster
- The sameNode function a. keey === B. Keey can be compared with the sameNode function a. keey === B. So it’s more accurate.
- Faster: using the uniqueness of the key to generate map objects to obtain the corresponding nodes, faster than traversal, the source code is as follows:
14, vue – the router
- Hash pattern
Early implementations of front-end routing were based on location.hash. The principle is simple: the value of location.hash is what comes after the # in the URL.
The hash routing mode is implemented based on the following features:
- The hash value in the URL is only a state of the client, that is, when a request is made to the server, the hash part will not be sent.
- Changes to the hash value add a record to the browser’s access history. So we can switch the hash through the browser’s back and forward buttons;
- You can use the a tag and set the href attribute. When the user clicks on the tag, the HASH value of the URL will change. Or use JavaScript to assign loaction.hash to change the HASH value of the URL.
- We can use the HashChange event to listen for changes in the hash value to jump (render) the page.
- The history mode
HTML5 provides the History API to implement URL changes. The two main apis are history.pushstate () and history.repalcestate (). Both apis allow you to manipulate the browser’s history without refreshing it. The only difference is that the former is a new historical record, the latter is a direct replacement of the current historical record
The history routing pattern is implemented based on the following features:
- PushState and repalceState apis to implement URL changes;
- We can use the PopState event to listen for URL changes to jump (render) the page;
- History.pushstate () or history.replacEstate () will not trigger the popState event, so we need to trigger the page jump (rendering) manually.
- abstract
Support for all JavaScript runtime environments, such as node.js server. If the browser API is not found, routing automatically forces the mode into this mode.
15. Route guard
- Global guard
- router.beforeEach((to,from,next)=>{})
- The arguments in the callback function, to: which route to enter, from: which route to leave, and next: function, determine whether to display the route page you want to see.
- Set global guard in router.js to determine whether to.path is the current path for login or registration. If so, execute next() to display the current interface. If not, alert will pop up and move to the login screen. In this way, the login interface is always displayed when the user is not logged in.
- Guards within components
- When this component is reached, beforeRouteEnter:(to,from,next)=>{}
- When leaving this component, beforeRouteLeave:(to,from,next)=>{}, and click on other components to determine whether to confirm leaving. Confirm next(); Cancel next(false) and leave on the current page.
16, vuex
Vuex is a state management mode developed specifically for vue.js applications. At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app.
- Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.
- The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change.
It mainly includes the following modules:
- State: Data structure that defines the State of the application, where the default initial State can be set.
- Getter: Allows the component to get data from the Store. The mapGetters helper function simply maps the getters in the Store to local computed properties.
- Mutation: is the only method that changes the state in the store, and must be a synchronization function.
- Action: Used to commit mutation rather than directly change the state, and can include any asynchronous operation.
- Module: Allows you to split a single Store into multiple stores and Store them simultaneously in a single state tree.
Vuex points module
- Create a good store warehouse directory in the project, divide the store into multiple modules, better and clearer management of their own projects. Each module has its own state, mutation, action, and getter.
- Create store (in index.js file)
17,vue.use
Vue.use() is used when using someone else’s component. For example: vue.use (VueRouter), vue.use (ElementUI)
18, vue components
- Create a file in the Components file
- Global references or file references in need (components)
19, vue. Config. Js
Vue. Config. js is an optional configuration file that is automatically loaded by @vue/cli-service if it exists in the root directory of the project (the same as package.json). You can also use the vue field in package.json, but note that this requires you to follow the JSON format strictly.
20,axios
Create instance: axios.create()Global configuration (lowest priority) : for example
- axios.default.timeout = 3000
- axios.default.baseURL = 3000
Request interceptorResponse interceptor
21. Common libraries
Vant element,
22, webpack
CSS preprocessing tool
SCSS:
- NPM install node-sass sass-loader -d
- Package. The json file
“DevDependencies” : {” node – sass “:” ^ 4.9.3 “, “sass – loader” : “^” 7.1.0,},
- Webpack. Base. Conf. Js file
23. SSR, PWA
- ssr
SSR roughly means that the whole HTML fragment rendered by VUE on the client side is completed on the server side, and the HTML fragment formed by the server side is directly returned to the client. This process is called server side rendering.
- Advantages of server-side SSR rendering:
- Better SEO: Because the content of SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the completion of Ajax asynchronism before grabbing the page content, so the content of SPA page obtained through Ajax cannot be captured; SSR is directly returned by the server to the rendered page (data has been included in the page), so the search engine crawler can grab the rendered page;
- Faster content arrival time (faster loading on the first screen) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. File download takes a certain amount of time, so rendering on the first screen takes a certain amount of time. SSR directly returns the page rendered by the server directly, without waiting to download JS files and render again, so SSR has a faster content arrival time;
- Disadvantages of server-side rendering:
- More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, resulting in some external extension libraries requiring special handling to run in server-side rendering applications; And unlike fully static single-page application SPA, which can be deployed on any static file server, server-side rendering applications need to be in the Node.js server running environment;
- More server load: Rendering a full application in Node.js is obviously more CPU-intensive than a server that only serves static files, so if you expect to use it in a high traffic environment, Prepare your server load and use caching strategies wisely.
- pwa
PWA stands for Progressive Web App, or Progressive Web application.
A PWA application is first and foremost a Web page, and a Web application can be written using Web technology. Then add App Manifest and Service Worker to realize PWA installation and offline functions. What problems have been solved?
- Can be added to the main screen, click the main screen icon can realize the start animation and hide the address bar
- Realize the offline cache function, even if the user’s mobile phone does not have the network, still can use some offline functions
- Message push is implemented
25. Unit testing
Vue unit tests
26, MVVM
Full name: model-view-viewModel, Model stands for data Model layer. The View represents the view layer, and the ViewModel is the bridge between the View and Model layer. Data is bound to the ViewModel layer and automatically rendered to the page. View changes notify the ViewModel layer to update data.
Vue is neither MVVM nor MVVM framework. It borrows ideas from the official MVVM framework, but may have its own unique architecture when implemented.
27, nextTick
Asynchronous methods, the last step in asynchronous rendering, are closely associated with THE JS event loop. Using macro tasks and microtasks (setTimeout, Promise, etc.), we defined an asynchronous method that would queue the method multiple calls to nextTick and clear the current queue asynchronously.
28. Initial rendering of VUE components
- The parse template is the Render function
The compiler function of vue-template-compiler (vUE) is used to render the vue template-compiler (VUE)
- Trigger response
Reactive key Object.defineProperty() binds the variables used in the template’s first rendering to Object.defineProperty(), which fires the getter for the first rendering
- Execute render function
Now that we have the render function, we need to execute the render function to convert the Vue syntax into the result of the H function, vNode, and then do a series of operations
29. Vue response
- Vue2
Object.defineproperty redefines all the attributes in data. Object.defineproperty can add an interception function to the data acquisition and setting, intercepting the acquisition of attributes for dependency collection. Intercepts property updates for notification.
- vue3
Proxy interception: Reactive wraps the target object passed to the Proxy, intercepts its get, set, etc., and caches the target of the Proxy to targetMap, targetmap.set (target, new Map()). The agent’s get calls a track function, and the set calls a triger function. This corresponds to dependency collection and triggered update.
30. Virtual DOM
- The realization principle of virtual DOM mainly includes the following three parts:
- JavaScript objects are used 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 a real DOM tree.
- How do I get from the real DOM to the virtual DOM
- Convert templates to AST trees that use objects to describe real JS syntax (convert real DOM to virtual DOM)
- Optimization of tree
- Generate code from the AST tree
- Pros and cons of the virtual DOM
Advantages: Guaranteed low performance: The framework’s virtual DOM needs to accommodate any operations that the upper API may produce, and some of its DOM operations must be implemented in a universal way, so its performance is not optimal; But performance is much better than rough DOM manipulation, so the framework’s virtual DOM can at least guarantee decent performance without having to manually optimize it. No need to manually manipulate the DOM: We no longer need to manually manipulate the DOM, just need to write the code logic of the View-Model, the framework will help us update the View in a predictable way according to the virtual DOM and data two-way binding, greatly improving our development efficiency; Cross-platform: The virtual DOM is essentially a JavaScript object, and the DOM is platform-dependent. In contrast, the virtual DOM can be more easily cross-platform, such as server rendering, WEEX development, and so on.
Disadvantages: No extreme optimization: Although reasonable optimization of virtual DOM + is enough to meet the performance requirements of most applications, virtual DOM cannot be optimized specifically in some applications with high performance requirements.
31. Diff algorithm
- Time complexity:
The complete diff algorithm of a tree is a time complexity O(n*3), which is optimized by VUE into O(n). To understand:
- Minimum updates. Key is important. This can be a unique identifier for the node, telling the Diff algorithm that they are the same DOM node before and after the change
- If a key is not used, it will be forcibly reused. For example, if a node is moved or a node is added (modifying the DOM), adding a key will only move and reduce the DOM operation.
- A fine comparison is performed only when the same virtual node is used. Otherwise, the old node is deleted and the new node is inserted.
- Comparisons are made within layers, not across layers.
- Diff algorithm optimization strategy: four matching search, four Pointers
- Old before and new before (start first, insert and delete nodes later)
- Old after and new after (compare ending, before insertion or deletion)
- Old before and new after (head to tail ratio, this happens, involves moving nodes, so the node pointing to the new before, moves to the old after)
- Old back to new front (tail to head ratio, this happens, involves moving the node, so the node pointing to the new front, moves to the old front before)
32. Vue performance optimization
- Coding optimization:
- The event agent
- keep-alive
- Break up the component
- Key guarantees uniqueness
- Route lazy, asynchronous components
- If the throttle
- Vue load performance optimization
- Import third-party modules on demand (babel-plugin-Component)
- Lazy loading of images
- The user experience
- App – skeleton frame screen
- Shellap p shell
- pwa
- SEO optimization
- pre-rendered