Summary of vUE interview questions

1. Vue and React

  • => Similarity:

    2. Both have virtual DOM, component-based development, and use props parameter to transfer data between parent and child components, which implements the webComponents specification 3. React has react Native, vue has WexxCopy the code
  • => Differences:

    1. Data binding: Vue implements two-way data binding, react data flows are one-way 2. 3. Usage scenarios: React and Redux architecture are suitable for large-scale multi-person collaboration complex projects, while Vue is suitable for small and fast projects 4. React Recommended approach JSX + inline style puts HTML and CSS in js. Vue uses webpack + VUE-loader single file component format, HTML, JS, CSS in one fileCopy the code

2. This section describes MVVM(bidirectional data binding

  • M: Model Data model
  • V: the view interface
  • MV: As a bridge, responsible for communication between View and model

  • Focus only on data flow and reduce strong coupling. The key is two-way data binding

    Key steps: 1. Implement data listener Observer, override data get/set with Object.defineProperty (). The value update notifies the subscriber in the set to update the data. 2. Implement the template compile, deeply traverse the DOM tree, replace the instruction template data for each element node, and subscribe data 3. The watch implementation connects the Observer with Compile, subscribles to and receives notification of each property change, and executes the corresponding callback function bound by the instruction to update data 4. Implement a subscriber Dep: The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformly.Copy the code

  • MVC and MVVM are not that different. It’s all a design idea. Basically, the Controller in MVC morphed into the viewModel in MVVM. MVVM mainly solves the problem that a large number of DOM operations in MVC reduce page rendering performance.

The loading speed is slow, which affects user experience. And when the Model changes frequently, developers need to actively update the View.

3. Life cycle functions

New Vue (create a Vue object) -- - > beforeCreate - > the observer Data (start monitoring Data object Data change) - > init event (Vue internal initialization events) - > created () - > Compile --> beforeMount --> mounted(compile the template, generate HTML from data and template) --> beforeMount --> beforeUpdate (Vritual Dom) --> updated --> beforeDestroy --> destroyedCopy the code
  • 1. Ajax requests are better placed in Created, and pages can now access this
  • 2. Operations on the DOM are placed inside mounted. The DOM is not generated before Mounted
  • 3. Do something every time you enter/leave a component, using what hook function:
    • No caching: Create and Mounted hooks can be used for entry, and beforedDestory and deStoryed can be used for departure
    • Caching: After caching a component, beforeCreate, created, beforeMount, and Mounted are not triggered on each entry of the component. If you want to do something every time you enter a component, you can put activated in the cache component hook

4. Tell me your understanding of SPA single page. What are its advantages and disadvantages?

  • SPA (Single-Page Application) loads the corresponding HTML, JavaScript, and CSS only when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page because of the user’s operation. Instead, routing mechanisms are used to transform HTML content, interact with the user and avoid page reloading.

  • Advantages:

    • User experience is good, fast, content change does not need to reload the whole page, avoid unnecessary jump and repeated rendering;

Based on the above point, SPA exerts less pressure on the server. The responsibilities of the front and back end are separated, and the architecture is clear. The front end carries out interactive logic, and the back end is responsible for data processing.

  • Disadvantages:

    • Time-consuming initial loading: To achieve single-page Web application functions and display effects, you need to load JavaScript and CSS in a unified manner. Some pages are loaded as required.

Forward and backward routing management: Because a single page application displays all content on a page, it cannot use the browser’s forward and backward function. All page switches need to build their own stack management. SEO is difficult: because all content is displayed dynamically on a page, SEO has a natural disadvantage.

5. How to optimize the loading speed of Vue SPA

Reduce the volume of imported files. 2. Local cache of static resources 3. Using SSR, nuxt. JsCopy the code

6. What’s the difference between v-show and V-if?

  • V-if is true conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch; Also lazy: if the condition is false during the initial render, nothing is done — the conditional block does not start rendering until the condition is true for the first time.
  • V-show is much simpler — elements are always rendered regardless of initial conditions, and simply switch based on the “display” property of CSS.
  • Therefore, V-IF is suitable for scenarios where conditions are rarely changed at runtime and do not need to be switched frequently; V-show is suitable for scenarios that require very frequent switching of conditions.

7. How to understand the one-way data flow of Vue?

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 situations when 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 this prop as its initial value:
props: ['initialCounter'],
data: function () {
  return {
    counter: this.initialCounter
  }
}

Copy the code
  • 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
props: ['size'],
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}

Copy the code

8. What are the differences between computed and Watch and the application scenarios?

  • Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, computed values will be recalculated the next time it obtains computed values.
  • Watch: It is more of a function of “observation”, similar to the listening callback of some data. Whenever the monitored data changes, the callback will be executed for subsequent operations.

Application scenario:

When we need to do numerical calculations and rely on other data, we should use computed, because we can take advantage of the caching nature of computed and avoid recalculating each time we get a value.

Watch should be used when we need to perform asynchronous or expensive operations when data changes. Using the Watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform that operation, and sets the intermediate state until we get the final result. These are all things you can’t do with computed properties.

9. Can Vue detect changes when assigning an array item directly?

Due to JavaScript limitations, Vue cannot detect the following array changes:

  • When you set an array item directly using an index, for example:vm.items[indexOfItem] = newValue
  • When you modify the length of an array, for example:vm.items.length = newLength

To solve the first problem, Vue provides the following operations:

Vue. Set Vue. Set (vm.items, indexOfItem, newValue) // Vue. $set(vm.items, indexOfItem, newValue) // array.prototype.splice vM. items. Splice (indexOfItem, 1, newValue)Copy the code

To solve the second problem, Vue provides the following operations:

// Array.prototype.splice
vm.items.splice(newLength)
Copy the code

Vue parent component and child component lifecycle hook function execution sequence?

Vue’s parent and child component lifecycle hook function execution sequence can be categorized into the following four parts:

  • Loading the rendering process

Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted

  • Child component update process

Parent beforeUpdate -> Child beforeUpdate -> Child updated -> Parent updated

  • Parent component update process

Parent beforeUpdate -> Parent updated

  • Destruction of the process

Parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyed

11. In which lifecycle is the asynchronous request invoked?

You can call hook functions created, beforeMount, and Mounted because in these three hook functions, data is already created and can be assigned to the data returned by the server. However, I recommend calling an asynchronous request from a Created hook function, because calling an asynchronous request from a Created hook function has the following advantages:

  • The server data can be obtained faster, reducing page loading time.
  • SSR does not support beforeMount and Mounted hook functions, so creating helps consistency.

12. At what stage can I access the manipulation DOM?

Before hook mounted is called, Vue has already mounted the compiled template to the page, so DOM can be accessed in Mounted. Vue life cycle diagram can be seen below, understand the operation of the entire life cycle phase, about the life cycle related interview questions are not difficult to you.

13. Can a parent component listen to the life cycle of a child component?

If the Parent component listens to the mounted component, then the Parent component does some logical processing.

// Parent.vue
<Child @mounted="doSomething"/>
    
// Child.vue
mounted() {
  this.$emit("mounted");
}

Copy the code

$emit triggers the parent component’s event manually. A simpler way is to use @hook to listen when the parent component references the child component, as shown below:

// Parent. Vue <Child @hook:mounted="doSomething" ></Child> doSomething() {console. '); }, // child.vue mounted(){console.log(' Child component raises mounted hook function... '); }, // The child component triggers the mounted hook function... // The parent listens to the mounted hook function...Copy the code

The @hook method not only listens for Mounted, but also for other lifecycle events, such as created, updated, etc.

14. Why does data in a component have to be a function and then return an object, while data in a new Vue instance can be an object?

// data data() {return {message: "child component ", childName:this.name}} // new Vue new Vue({el: '#app', router, template: '<App/>', components: {App} })Copy the code

If data is an object in a component, then the scope is not isolated. The data property values in the subcomponent will affect each other. If the data option in a component is a function, then each instance can maintain an independent copy of the returned object. Data property values between component instances do not affect each other; The instance of new Vue is not reused, so there is no object reference problem.

15. How does v-Model work?

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 for different input elements and throws different events:

  • 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.

Take the input form element for example:

<input V-model ='something'> equivalent to <input v-bind:value="something" V-on :input="something = $event.target.value">Copy the code

If in a custom component, the V-Model defaults to use a prop named Value and an event named input, as follows:

Parent: <ModelChild V-model ="message"></ModelChild> Child: <div>{{value}}</div> props:{value: String}, methods: {test1(){this.$emit('input', 'red ')},},Copy the code

16. What are the ways of communication between Vue components?

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.

(1) Props / $emit can be used for parent-child component communication. This method is the basis of Vue component communication.

(2) ref and $parent / $children are suitable for parent-child communication

  • refIf 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 / $children: Accesses the parent/child instance

EventBus ($emit / $on) is a method that uses an empty Vue instance as the central EventBus (event center) to trigger events and listen for events, thus implementing communication between any components including parent, child, and sibling components.

$listeners are suitable for intergenerational component communication

  • $attrs: contains property bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop. When a component does not declare anypropThis contains all parent-scoped bindings (except class and style) and can pass v-bind="$attrs"Pass in internal components. Usually cooperateinheritAttrsOption used together.
  • $listeners: contains the parent scope (without the.native modifier)v-onEvent listeners. It can go throughv-on="$listeners" Passing in internal components

(5) Provide/inject this function is applicable to provide/inject variables by provider in the communication ancestor component, and inject variables in the descendant component. 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 a state management mode specially developed 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.

17. Have you ever used 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.

(1) The state storage of Vuex is responsive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.

(2) The only way to change the state in a store is to explicitly commit mutation. 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.

18. Have you used Vue SSR? Tell me something about the SSR?

Vue.js is a framework for building client applications. By default, the Vue component can be exported to the browser for DOM generation and DOM manipulation. However, it is also possible to render the same component as server-side HTML strings, send them directly to the browser, and finally “activate” these static tags into a fully interactive application on the client side.

That is, SSR roughly means that vUE renders the entire HTML fragment of the label on the client side and completes the work on the server side. The HTML fragment formed by the server side is directly returned to the client side. This process is called server side rendering.

Advantages and disadvantages of server rendering SSR are as follows:

(1) Advantages of server-side 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;

(2) 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.

19. How many vue-router routing modes are there?

Vue-router has three routing modes: hash, history, abstract. The corresponding source code is as follows:

switch (mode) { case 'history': this.history = new HTML5History(this, options.base) break case 'hash': this.history = new HashHistory(this, options.base, this.fallback) break case 'abstract': this.history = new AbstractHistory(this, options.base) break default: if (process.env.NODE_ENV ! == 'production') { assert(false, `invalid mode: ${mode}`) } }Copy the code

The three routing modes are described as follows:

  • Hash: Uses the URL hash value for routing. Support for all browsers, including those that don’t support the HTML5 History Api;

  • History: Relies on the HTML5 History API and server configuration. See the HTML5 History mode;

  • Support all JavaScript runtime environments, such as node.js server side. If the browser API is not found, routing automatically forces the mode into this mode.

20. Can you explain the hash and history routing modes used in vue-router?

(1) Implementation principle of hash mode

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. For example, here’s a website whose location.hash value is ‘#search’ :

https://www.word.com#search
Copy the code

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.

(2) The realization principle of 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 to add a history, while the latter is to replace the current history directly, as shown below:

window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);
Copy the code

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.

21. How does Vue framework implement object and array listening?

If you were asked how Vue implemented bidirectional data binding, you would probably answer that it hijacks data via Object.defineProperty(), but object.defineProperty () can only hijack attributes, not whole objects. Similarly, arrays cannot be hijacked, but we know from using the Vue framework that Vue can detect changes in objects and arrays (partial method operations). How does this work? We look at the relevant code as follows:

/** * Observe a list of Array items. */ observeArray (items: Array<any>) { for (let i = 0, l = items.length; i < l; I ++) {observe(items[I]) // Observe (items[I])}} /** * Recurse attributes */ let childOb =! Shallow && observe(val) // Observe changes in dataCopy the code

From the Vue source section above, we can see that the Vue framework is able to listen for objects and arrays (partial method operations) using Object.defineProperty() by iterating through groups of numbers and recursively traversing objects.

22. Comparison between Proxy and Object.defineProperty

Advantages of Proxy are as follows:

  • Proxies can listen directly on objects rather than properties;
  • Proxy can listen for array changes directly;
  • Proxy has up to 13 interception methods, not limited to apply, ownKeys, deleteProperty, has, etc. Object. DefineProperty does not have;
  • Proxy returns a new Object. We can only manipulate the new Object to achieve our purpose. Object.defineproperty can only be modified by iterating through Object attributes.

Proxy as the new standard will be subject to browser vendors focus on continuous performance optimization, which is the legendary performance bonus of the new standard;

Object.defineproperty has the following advantages:

  • It has good compatibility and supports IE9, but Proxy has browser compatibility problems and cannot be smoothed by Polyfill. Therefore, the author of Vue announced that Proxy can be rewritten until the next big version (3.0).

Vue uses vm.$set() to respond to new attributes.

Restricted by modern JavaScript, Vue cannot detect the addition or deletion of object attributes. Since Vue performs getter/setter conversions on the property when it initializes the instance, the property must exist on the data object for Vue to convert it to reactive. $set (object, propertyName, value)/vm.$set (object, propertyName, value)/Vue.

We view the corresponding Vue source: Vue/SRC/core/instance/index. Js

export function set (target: Array<any> | Object, key: any, val: any): Any {// target isArray if (array.isarray (target) &&isvalidarrayindex (key)) { Target.length = math.max (target.length, key) // Use the array splice method to trigger the response target.splice(key, 1). Val) return val} if (key in target &&! (key in Object.prototype)) { target[key] = val return val } const ob = (target: Any).__ob__ // Target itself is not a response data, directly assigned if (! Ob) {target[key] = val return val} defineReactive(ob.value, key, val) ob.dep.notify() return val}Copy the code

$set vm.$set vm.$set

  • If the target is an array, use the array splice method directly to trigger the corresponding expression.
  • If the target is an object, the presence of the attribute and whether the object is reactive are first read. Finally, if the attribute is to be processed responsively, it is processed responsively by calling the defineReactive method (the defineReactive method is when Vue initializes the object, Method called to dynamically add getters and setters to Object properties using Object.defineProperty)

24. Pros and cons of the virtual DOM?

Advantages:

  • Lower performance: The framework’s virtual DOM needs to accommodate any operations that the upper-level 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:

  • Extreme optimization cannot be carried out: Although reasonable optimization of virtual DOM + is sufficient to meet the performance requirements of most applications, targeted extreme optimization cannot be carried out in some applications with extremely high performance requirements.

25. How does virtual DOM work?

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.

  • Virtual DOM detailed article

26. V – HTML

  • How does V-HTML solve XXS attack and its principle

27. What is the role of key in Vue?

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:

function createKeyToOldIdx (children, beginIdx, endIdx) {
  let i, key
  const map = {}
  for (i = beginIdx; i <= endIdx; ++i) {
    key = children[i].key
    if (isDef(key)) map[key] = i
  }
  return map
}
Copy the code

28. What optimization did you make for the Vue project?

If you have not summarized the optimization of THE Vue project, you can refer to another article “Vue Project Performance Optimization – Practical Guide”, which mainly introduces how to optimize the Vue project from 3 major aspects and 22 small aspects in detail.

(1) Optimization at the code level

  • V-if and V-show are used in different scenarios
  • Computed and Watch distinguish usage scenarios
  • V-for traversal must add a key to the item and avoid using v-if at the same time
  • Long list performance optimization
  • Destruction of events
  • Lazy loading of image resources
  • Route lazy loading
  • The introduction of third-party plug-ins on demand
  • Optimize infinite list performance
  • Server render SSR or prerender

(2) Optimization of Webpack level

  • Webpack compresses images
  • Reduce redundant code from ES6 to ES5
  • Extract common code
  • Template precompilation
  • Extract the COMPONENT’s CSS
  • Optimize SourceMap
  • Build results output analysis
  • Compilation optimization of Vue project

(3) Optimization of basic Web technology

  • Enable Gzip compression
  • Browser cache
  • The use of CDN
  • Use Chrome Performance to find Performance bottlenecks

29. The modular

  • Basic Concepts:
  1. In JS, a module is a file that implements a specific function (js file)

  2. Follow the module mechanic and load whatever module you want

  3. Modular development needs to follow specifications

  • Js implements the modular specification

    1. The REQUIREjs module of AMD browser is loaded asynchronously, and the module loading does not affect the running of the following statements. The default path parsing mode of baseURL+ Paths is 2.commonjs nodejs 3Copy the code
  • Problems solved: 1. naming conflict 2. file dependency 3. module reuse 4. Unify specifications and development methods

30. Talk about componentization of Vue and React

  • 1. During the development of various pages, there will be many repetitive functions, such as XXXX in Element. Purely non-page UIs like this became the UI component we used to use, and the original front-end component was just a UI component
  • 2. As business logic becomes more and more complex, we want our components to be able to do a lot of things. This is what we call componentization
  • 3. The idea is to divide and conquer. Minimizing development difficulty and maintenance costs. You can also collaborate with multiple people, each writing a different component and eventually building it up like building blocks

31. What do you know about the upcoming vue3.0 features?

Vue 3.0 is well on its way to release. The goal of Vue 3.0 is to make the Vue core smaller, faster, and more powerful, so Vue 3.0 adds these new features:

(1) Change of monitoring mechanism

3.0 will bring a proxy-based Observer implementation that provides reactive tracing with full language coverage. This removes many of the limitations of the object.defineProperty-based implementation in Vue 2:

  • Only properties can be monitored, not objects

  • Detect the addition and removal of attributes;

  • Detect array index and length changes;

  • Supports Map, Set, WeakMap, and WeakSet.

The new Observer also provides the following features:

  • A public API for creating Observables. This provides a simple and lightweight cross-component state management solution for small to medium scale scenarios.
  • Lazy observation is used by default. In 2.x, no matter how large the equation data is, it will be observed at startup. If your data set is large, this can cause significant overhead at startup time. In 3.x, only the data used to render the first visible part of the application is observed.
  • More accurate notification of changes. In 2.x, forcing a new attribute through vue.set causes the Watcher that depends on the object to be notified of the change. In 3.x, only the Watcher that depends on a particular property is notified.
  • Immutable Observable: We can create “immutable” versions of values (even nested properties) unless the system temporarily “unlocks” them internally. This mechanism can be used to freeze prop transfers or changes outside the Vuex state tree.
  • Better debugging: We can use new renderTracked and renderTriggered hooks to track exactly when and why components are being rerendered.

(2) Template

There were no major changes to the template, only the scope slots were changed. 2.x changed the scope slots and the parent component was re-rendered, while 3.0 changed the scope slots to function mode, which only affected the re-rendering of child components and improved rendering performance.

As for the render function aspect, vue3.0 will also make a number of changes to make it easier to use the API directly to generate the VDOM.

(3) Object-type component declaration

Components in vue2. X pass in a set of options declaratively, and TypeScript is combined with decorators, which are functional but cumbersome. 3.0 changes the way components are declared to be class-like, making it easy to integrate with TypeScript.

In addition, the source code for Vue is written in TypeScript. In fact, when the functionality of the code is complex, it is necessary to have a static type system to do some auxiliary management. Now vue3.0 is fully rewritten in TypeScript, making it easier for exposed apis to incorporate TypeScript. Static type systems are really necessary for the maintenance of complex code.

(4) Changes in other aspects

The changes to VUe3.0 are comprehensive, with only three major areas covered above, as well as some other changes:

  • Support for custom renderers, which allows WEEX to be extended by custom renderers instead of forking the source code.
  • Fragment (multiple root nodes) and Protal (rendering components in other parts of the DOM) components are supported for specific scenarios.
  • Based on Treeshaking optimization, more built-in features are provided.

32. Do you know which Web template engine vue uses for template syntax? Tell me what you understand about the template engine

Vue uses Mustache syntax, which is the syntax of double braces.

Template engine: Responsible for assembling data and presenting it in another form or appearance.

Advantages:

  • Maintainability (easy to change later);
  • Scalability (want to increase functionality, increase demand convenience);
  • Improved development efficiency (better program logic organization, easy debugging);
  • Look comfortable (not easy to write wrong)

32. Do you know which Web template engine vue uses for template syntax? Tell me what you understand about the template engine

Vue uses Mustache syntax, which is the syntax of double braces.

Template engine: Responsible for assembling data and presenting it in another form or appearance.

Advantages:

  • Maintainability (easy to change later);
  • Scalability (want to increase functionality, increase demand convenience);
  • Improved development efficiency (better program logic organization, easy debugging);
  • Look comfortable (not easy to write wrong)

33. How to define global methods for VUE?

First: mount to Vue prototype. Write the global method to a file and then mount the for loop to Vue’s Prototype. The drawback is that this method is called without prompting

 Object.keys(tools).forEach(key => {
      Vue.prototype[key] = tools[key]
 })
Copy the code

The second is to globalize mixins, because the methods in mixins are merged with each single-file component you create. This has the advantage of being prompted when the method is called

Vue.mixin(mixin) new Vue({ store, router, render: h => h(App), }).$mount('#app') import tools from "./tools" import filters from "./filters" import Config from '.. /config' import CONSTANT from './const_var' export default { data() { return { CONFIG: Config, CONSTANT: CONSTANT } }, methods: {// // mount methods from Tools to vue for easy call, Prototype [key] => {// Vue. Prototype [key] = tools[key] //} This.$XXX is the name of this.$XXX method. tools }, filters: // object.keys (filters).foreach (key => {// vue. Filter (key, filters[key]) //})... filters } }Copy the code

34. Vue2.0 no longer supports filters in v-html.

  • Define methods in method
htmlFilter(htmlString){
return htmlString.replace(/+s/g,'')
}
Copy the code
  • In vUE v-html=”htmlFilter(htmlString)” can be

35. How to solve the problem of invalid static resource images after VUE packaging?

Change assetsPublicPath: ‘/’ to assetsPublicPath: ‘./’

In the latest vue-CLI, you need to create a vue.config.js file in the root directory to configure publicPath