preface

This article sorted out the front-end high-frequency VUE test points, if you have different views on the answer of the students welcome to the comment section of supplementary discussion, of course, there are questions, also welcome to point out in the comment section.

Source juejin. Cn/post / 698421…

Detailed version segmentfault.com/a/119000001 vue note…

Juejin. Cn/post / 684490… supplement

1. The advantages of vue

  • Lightweight framework: Focuses only on the view layer and is only tens of kilobytes in size

  • Easy to learn: Chinese developed, Chinese documents, easy to understand and learn;

  • Two-way data binding: Preserves Angular features and makes data manipulation easier;

  • Componentalization: Retain the advantages of React and realize the encapsulation and reuse of HTML, which facilitates the construction of single-page applications.

  • Separation of view, data and structure: it makes it easier to change the data, without the need to modify the logical code, and only need to operate the data to complete the relevant operations;

  • Virtual DOM: DOM manipulation is very performance-intensive; use VDom+ DIff instead

  • Faster operation: Compared with React, vUE also operates virtual DOM and has better performance.

Disadvantages: Single page is not conducive to SEO, long time to load the main page for the first time (SSR solution)

2. Vue is the understanding of progressive framework

You can use only parts of me, not all parts of me (e.g., Component if you want, don’t use it, vuex if you want, don’t use it)

3. Similarities and Differences between Vue and React

Similarities:

  • 1. Both use the virtual DOM
  • 2. Componentized development
  • 3. One-way data flows (between parent and child components, it is not recommended that the child modify the data transmitted from the parent)
  • 4. Both support server rendering
The difference between vue react
Monitoring data changes Vue hijacks data via defineProperty to listen for data changes. Vue emphasizes variable data React does not monitor data precisely because React emphasizes immutable data
Different life cycles
Data state management vuex redux
Dom manipulation is very convenient, the for directive, the if directive More beautiful code
Differences in data flow There is a two-way data flow (V-Model) between components and DOM, and one-way data flow (props) between parent and child One-way data flow between parent and child (props) and between component and DOM (state)

4. Difference between MVVM and MVC

MVC

  • Model: Is responsible for fetching data from the database
  • View: The interface responsible for displaying data
  • Controller: A place where users interact, such as click events, etc
  • Idea: The Controller displays the Model’s data on the View

MVVM

  • VM (View model) : realize the two-way binding of data, (1) convert the data passed by the back end into the page seen. (2) Convert the page you see into back-end data
  • Idea: Vue data driven, that is, the corresponding view layer display automatically changes after data changes
  • Vue is not strictly compliant with MVVM, because MVVM specifies that Model and View cannot communicate directly, whereas VUE’srefYou can do that

7. Why is data a function and returns an object?

Data has only one function because a component may be called multiple times, and each call executes the data function and returns a new data object, thus avoiding data contamination between multiple calls.

8. What Vue modifiers have you used?

Check out the 13 favorite Vue modifiers interviewers ask about in this article

9. What internal Vue directives have you used?

  • V-once once bound, data does not change
<template>
    <div>
        <h3>v-once</h3>
        <input type="text" v-model="voncetext" />Enter test V-once123<p>{{voncetext}}</p>V - once123 test<p v-once>{{voncetext}}</p>Test v - once</div>
</template>
​
<script>
    export default({
        name:"voncetest".data(){
            return{
                voncetext:"Test v - once"
            }
        }
    })
</script>
Copy the code

10. What are the modes of value transfer between components (communication)?

  • The parent component passes a value to the child component, which uses itpropsTo receive
  • The child component passes values to the parent component, which the child component uses$emit + eventPass values to the parent component
  • Component can be used in$parentand$childrenGet the parent and child component instances, and then get the data
/ / the parent component
mounted(){
  console.log(this.$children) 
  // Get the attributes and methods of the child components
  // You can change data directly, or call methods
}
​
/ / child component
mounted(){
  console.log(this.$parent) // We can get the properties and methods of parent
}
Copy the code
  • use$attrsand$listenersIn the secondary encapsulation of some components, such as A->B->C, values can be easily transmitted
1.In the attrs scenario, if the parent has a lot of values, then the child component needs to define multiple props. In the attrs scenario, if the parent has a lot of values, then the child component needs to define multiple propsprops: {
  width: {
    type: String.default: ' '}},mounted() {
  console.log(this.$attrs) //{title: "this is the title ", height: "80", imgUrl: "imgUrl"}
},
​
2.Notice Scenarios: Methods of the parent component need to be called by the child component. Methods of the parent component can be accessed using v− ON ="listeners"Passing in internal components - useful when creating higher-level components/ / the parent component
<home @change="change"/>
​
/ / child component
mounted() {
  console.log(this.$listeners) // Get the change event
}
Copy the code
  • use$refsGet the component instance, which in turn gets the data
/ / the parent component
<home ref="home"/>
​
mounted(){
  console.log(this.$refs.home) // Get an instance of a subcomponent and manipulate data and methods directly
}
Copy the code
  • useVuexPerform status management store
State: Defines the repository to store data, which can be accessed through this.$store.state or mapState. Here you can set the default initial state getter: allows the component to get data from the Store, which can be considered a computed property of the Store, accessed (computed) mutation: synchronizes changes through this.$store.getter or mapGetters Vue records the operation. If it is asynchronous, the changes cannot be traced. Available via mapMutations. Action is the only method to change the state in the store: asynchronously calling the function to perform mutation, thereby changing the store value, which can be accessed via this.$dispatch or mapActions Modules: If there are too many states, you can split them into modules, and finally pass the... The introduction of deconstructionCopy the code
  • useeventBusCross component trigger events that pass data
@method $on event subscription to listen for custom events on the current instance. Must register before event broadcast ($EMIT); @method $off Unsubscribes to events and removes custom event listeners. The @method $EMIT event broadcast must occur in conjunction with the event subscription ($ON), triggering the @method $once event subscription on the current instance, listening for a custom event, but only once, and removing the listener after the first event.Copy the code
//event-bus.js creates the event bus and exports it for easy invocation
import Vue from 'vue'
export const $EventBus = new Vue()
​
// main.js global event bus
Vue.prototype.$EventBus = new$once(channel: String, callback(payload1,...)) ) A component beforeDestroy () {// Event broadcast
    this.$EventBus.$emit('testing', color)} B component created () {// Event subscription
    this.$EventBus.$on('testing'.(res) = > { console.log(res) })
},
beforeDestroy () {
    this.$EventBus.$off('testing')}Copy the code
  • $root
/ / the parent component
mounted(){
  console.log(this.$root) // Get the root instance. Finally, all components are mounted to the root instance
  console.log(this.$root.$children[0]) // Get the first level child component of the root instance
  console.log(this.$root.$children[0].$children[0]) // Get the secondary child component of the root instance
}
Copy the code
  • Modifier. The sync
/ / the parent component
<home :title.sync="title" />
// Will be extended to
<home :title="title"  @update:title="val => title = val"/>/ / child component
// So the child component can change via $emit to trigger the update method
mounted(){
  this.$emit("update:title".'This is the new title')}Copy the code
  • useprovideandinjectWe’re officially advised not to use this. I’m reading itElementUISource code found when a lot of use
Mainly provides use cases for high-level plug-in/component libraries. Direct use in application code is not recommended;Copy the code
  • Use browser local caching, for examplelocalStorage

12. How to set dynamic class, dynamic style?

  • Dynamic class objects:<div :class="{ 'is-active': true, 'red': isRed }"></div>
  • Dynamic class array:<div :class="['is-active', isRed ? 'red' : '' ]"></div>
  • Dynamic style objects:<div :style="{ color: textColor, fontSize: '18px' }"></div>
  • Dynamic style array:<div :style="[{ color: textColor, fontSize: '18px' }, { fontWeight: '300' }]"></div>

13. What is the difference between v-if and V-show? V-for and V-if cannot be used together

  • 1.v-ifExplicit implicit control is implemented by controlling the deletion and generation of DOM elements, which determines the generation and destruction of components
  • 2.v-showExplicit implicit is implemented by controlling THE CSS style of DOM elements without destruction
  • 3. Frequent or large amount of explicit and implicit usev-show, otherwise usev-if

V-for and V-if should not be used together, and should be replaced with computed attributes if necessary.

  • Reason: V-for takes precedence over V-if. If you need to traverse the entire array every time, it will affect speed, especially if it requires a small part of the rendering.

Vue Advanced Interview questions

1.<keep-alive></keep-alive>What is the function of?

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering.

Keep-alive gives us three properties:

  • Include: accepts string or regular expression values. Only matching values are cached
  • Exclude: accepts a string or regular expression. The matched route will not be cached.
  • Max: indicates the maximum number of cache components

Caching of components:

// Cache only components whose name is a or B
<keep-alive include="a,b">
 <component :is="currentView"/>
</keep-alive>
​
// The component named c is not cached
<keep-alive exclude="c">
 <component :is="currentView"/>
</keep-alive>
​
// If both include and exclude are used,exclude takes precedence over include. In this example, only a component is cached
<keep-alive include="a,b" exclude="b">
 <component :is="currentView"/>
</keep-alive>
​
// If the number of cached components exceeds 5, the first cached component will be deleted
<keep-alive exclude="c" max="5">
 <component :is="currentView"/>
</keep-alive>
Copy the code

Caching of routing components:

Keep-alive can be used to cache all the routing components matched by the path, including those in the routing component.

<keep-alive> // If some components do not need caching, add the exclude attribute as above
 <router-view />
</keep-alive>
Copy the code

Partial route caching can also be implemented

  1. By adding in the meta attributekeepAliveProperties for
{
    path: '/login'.name: 'login'.meta: {
        keepAlive: false // Set no cache}}, {path: '/argu'.name: 'argu'.component: () = > import('@/views/argu.vue'),
    meta: {
        keepAlive: true // Set the cache}},Copy the code
  1. $route = keepAlive; $route = keepAlive; $route = keepAlive;
<template>
  <div id="app">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view> 
    </keep-alive>
    <router-view v-if=! "" $route.meta.keepAlive"></router-view>
  </div>
</template>
Copy the code
  1. When a component is wrapped around a keep-alive component, there are two additional hook functions: activated() and deactivated().
  • Activated (): This hook function is called when the component is first rendered and then each time the cache component is activated.

  • Deactivated () : called when the component is disabled (removed from the route).

  • Keep-alive components do not trigger beforeDestroy() and destroyed() because the component is not destroyed but cached.

  • The order in which the hook functions are called from entering a caching component is important:

    • Enter a cache component: Deactivated (this hook is available if it is entered from another cache component, otherwise none) — > Mounted — > Activated — > Execute the beforeRouteLeave callback.
    • Leaving a cache component: beforeRouteLeave — > global front-guard beforeEach — >deactivated Leaving the current component — > Activated (if entering a cache component, otherwise none)

2. How do I get the DOM?

Set ref=”domName” —— in the component

3. Use of V-Model.

The V-Model is used for bidirectional binding of form data, which is essentially a syntax sugar. There are two operations behind this:

  • V-bind binds a value attribute;
  • The V-on directive binds the input event to the current element.

4. Name the use of each folder and file in the SRC directory in vue-CLI project.

  • Assets folder is to put the style files js files required by the template in the project, go packing, reduce the volume
  • Components;
  • Router defines routing configurations.
  • App. vue is an application main component;
  • Main.js is the entry file.

Files in the static/ directory are not processed by Webpack and are copied directly to the final directory (dist/static by default) when packaged.

  • Stores third-party resource files introduced in the project, such as iconfoont. CSS
  • Any onstatic/The file needs to be referenced as an absolute path:/static/[filename]. This is done through theconfig.jsIn the filebuild.assetsPublicPath 和 build.assetsSubDirectoryLink to determine.

5. Describe the usage scenarios of computed, Watch, and filter respectively

computed:

Computations are needed when an attribute is affected by multiple attributes, and are suitable for complex data conversion and statistics scenarios

  • Typical chestnut: shopping cart checkout time
  • The computed property has caching capability, as follows: When index changes from 0 to 1, it triggers a view update, and methods executes again, but computed does not, because num and price, the two variables that computed depends on, remain unchanged
<div>
    <div>{{howMuch1()}}</div>
    <div>{{howMuch2()}}</div>
    <div>{{index}}</div>
</div>
​
data: () {
    return {
         index: 0}}methods: {
    howMuch1() {
        return this.num + this.price
    }
  }
computed() {
    howMuch2() {
        return this.num + this.price
    }
  }
Copy the code
watch:

When one data affects multiple data sets, watch is needed. Chestnut: Search for data

  • When we listen for a basic data type:
watch: {
    value () {
        // do something}}Copy the code
  • When we listen on a reference data type:
docData: {/ / object
            'doc_id': 1.'tpl_data': 'abc'
        }
​
watch: {
    docData: {
       handler () { // Perform the callback
           // do something
       },
       deep: true.When you need to listen for changes in an object, the normal watch method cannot listen for changes in the internal properties of the object
       immediate: true // Whether to execute the handler function when the component is initialized}}Copy the code
The filter:

Filter cannot be cached, is called frequently, and is suitable for formatting output scenarios, such as date formatting

  1. Global filter

    • Use a single filter through interpolation

      {{msg | upper}}

    • Use multiple filters by superimposing interpolation expressions

      {{msg | upper | lower}}

      The data is formatted twice, first to size, then to lowercase, and finally to render lowercase results

    • // main.js
      import Vue from "vue"
      import App from "./App.vue"
      ​
      Vue.filter('upper'.function(val){
          return val.charAt(0).toUpperCase()+val.slice(1)
      })
      Vue.filter('lower'.function(val){
          return val.charAt(0).toLowerCase()+val.slice(1)})new Vue({
          el:"#app".render(h){
              returnh(App); }})Copy the code
    • Format the value of the property binding by using filters

      <div v-bind:id="id | formatId">Test</div>

  2. Local filter

<template>
  <div>
    <input type="text" v-model="msg">
    <div>{{msg|upper}}</div>
    <button @click="handle(test)">Test the methods method call filter</button>
  </div>
</template>
​
<script>
  export default {
    data(){
      return {
        msg:'hzy'.test:'hello'}},filters: {upper(val){
        return val.charAt(0).toUpperCase()+val.slice(1)}},methods: {handle(val){
        // Use this.$options.filters[] to get local filters
        let localFilter = this.$options.filters['upper'];
        // Call local filter formatting
        localFilter(val);
      }
    }
  }
</script>
Copy the code

6. Can V-ON listen on multiple methods?

Can, chestnut: < input type = “text” v – on = “{input: the onInput, focus: an onFocus, the blur: onBlur,}” >.

7. What should be done with data that does not require responsiveness?

In our Vue development, there will be some data, from beginning to end all have not changed, the death data, now that don’t change, that also don’t need to be responsive to him processing, otherwise will only do some useless consumption performance, such as some writing death drop-down box, die form data, the data of death data, if all responsive processing, That will consume a lot of performance.

// Define data outside of data
data () {
    this.list1 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list2 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list3 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    return{}}// Freeze ()
data () {
    return {
        list1: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list2: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list3: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
    }
 } 
Copy the code

8. Parent component lifecycle order

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

9. New object properties cannot update the view. Deleting properties cannot update the view. How to do?

  • Reason: Object.defineProperty does not attribute hijack the new property of the Object

  • $set(obj, key, value); $set(obj, key, value)

  • Vue.$delete(obj, key); this.$delete(obj, key);

    • Delete simply changes the deleted element to empty/undefined and the other elements’ keys remain the same.

    • Vue.delete directly deletes the array and changes its key value.

    • Arr [0,1,2,3], uses delete to delete the second element, leaving the elements with the same keys as the original array. arr[0]=0; Arr [2] = 2; Arr [3] = 3; Where a[1] is empty

    • If vue. Delete is used, arr[0]=0; arr[1]=2; arr[2]=3

10. Custom instructions

See this article for 8 very useful Vue custom directives

11. How does the slot work?

Do you really know how to “insert” a Slot

A. Anonymous slot (also called default slot): there is only one anonymous slot.

// Parent component calls child component
<todo-list> 
    <template v-slot:default>Any content<p>I'm anonymous slot</p>
    </template>
</todo-list> 
​
// Child todolist.vue<slot> I am the default </slot>//v-slot:default
Copy the code

B. Named slot: relatively anonymous slot component slot labels are named by name.

// Parent component, the child of the call
<todo-list> 
    <template v-slot:todo>Any content<p>I'm anonymous slot</p>
    </template>
</todo-list> 
​
/ / child component
<slot name="todo"> I am the default </slot>Copy the code

C. Scope slot: The parent component can get the data of the child component

/ / the parent component
<todo-list>
 <template v-slot:todo="slotProps" >
   {{slotProps.user.firstName}}
 </template> 
</todo-list> 
//slotProps can be named at will
//slotProps is a set of attribute data on the subcomponent tag slot. All v-bind:user="user"/ / child component
<slot name="todo" :user="user" :test="test">
    {{ user.lastName }}
</slot> 
data() {
    return {
      user: {lastName:"Zhang".firstName:"yue"
      },
      test: [1.2.3.4]}},// {{user.lastName}} is the default data v-slot:todo when the parent page does not (="slotProps")
Copy the code

12. Why not use index as the key and random number as the key?

Here’s an example:

<div v-for="(item, index) in list" :key="index">{{item.name}}</div>
list: [
    { name: 'Ming'.id: '123' },
    { name: 'little red'.id: '124' },
    { name: 'flower'.id: '125'}] render as <div key="0"Xiao Ming > < / div ><div key="1">The little red</div>
<div key="2">The little flower</div>Now I call list.unshift({name: 'xiao Lin'.id: '122'}) render to <div key="0"> kobayashi < / div ><div key="1">Xiao Ming</div>
<div key="2">The little red</div>
<div key="3">The little flower</div>New vs. new <div key="0"Xiao Ming > </div> 
      
Xiaolin </
div> <div key="1">The little red</div> <div key="1">Xiao Ming</div> <div key="2">The little flower</div> <div key="2">The little red</div>                         <div key="3">The little flower</div><div key= <div key= <div key= <div key= <div key="123"Xiao Ming > < / div ><div key="124">The little red</div> <div key="125">The little flower</div>Now I call list.unshift({name: 'xiao Lin'.id: '122'}), render as <div key="122"> kobayashi < / div ><div key="123">Xiao Ming</div> <div key="124">The little red</div> <div key="125">The little flower</div>New vs. new <div key="122"> kobayashi < / div ><div key="123">Xiao Ming</div> <div key="123">Xiao Ming</div> <div key="124">The little red</div> <div key="124">The little red</div> <div key="125">The little flower</div> <div key="125">The little flower</div>It can be seen that the original three are unchanged, but the addition of xiao Lin this person, this is the most ideal resultCopy the code

Using index is the same as using random number. Random number changes every time, so it can’t be specific and it also consumes performance

13. What nextTick does

When you modify the value of data and immediately retrieve the dom element value, you cannot retrieve the updated value. You need to use the $nextTick callback to render the modified data value and update it to the DOM element before retrieving it.

<div ref="testDiv">{{name}}</div>
​
name: 'xiao Lin'this.name = 'Lin Three Hearts'   // Modify variables
console.log(this.$refs.testDiv.innerHTML) // What is here
Copy the code

The answer is “Kobayashi”, as mentioned above, Vue updates asynchronously, so when data is updated, the view is not updated yet, so it still gets the old view data (before DOM update).

this.name = 'Lin Three Hearts'
this.$nextTick(() = > {
    console.log(this.$refs.testDiv.innerHTML) / / Lin three hearts
})
Copy the code

14. What is SSR of Vue? What are the benefits?

  • SSRIt’s server side rendering
  • Based on thenodejsService environment development, allhtmlThe code is rendered on the server side
  • The rendered data (HTML) is returned to the front end, which then “activates” it and becomes HTML code that the browser recognizes
  • SSR optimized the first page loading and prevented crawlers

15. How is bidirectional data binding implemented in Vue?

See the details here: Observer and Publish subscriptions in Vue

To keep the data and the view in sync, the data changes, the view changes, the view changes, the data changes;

  1. Data listener observer: Add all Watcher classes to the Dep class (a container for message management) by using data hijacking, using the getter of Object.defineProperty() to listen for each property with a Watcher class, one for each property. When a property changes, setter functions are fired to modify the property value and re-add the new property value to the Dep class by adding the Watcher class. Dep.notify () then executes the compiler bound update function
  2. Instruction parser: Parses the instructions of each element node, replaces the data according to the instruction template, and binds the corresponding update function
  3. Watcher: Acts as a bridge between the observer and compiler, updating views by subscribing to and receiving notification of changes to each property and executing the corresponding callback function of the instruction binding
class Dep{
    constructor(){
        this.subs = [] // Store all the watcher
    }
    / / subscribe
    addSub(watcher){ / / add a watcher
        this.subs.push(watcher)
    }
    / / release
    notify(){
        this.subs.forEach(watcher= >watcher.updata()); }}Copy the code
class Observer{
    constructor(data) {
        this.observer(data);
    }
    observer(data){
        // Only if it is an object
        if(data && typeof data === 'object') {for (let key in data) { // Loop through all the children of data
                this.defineReactive(data,key,data[key]); }}}// Implement data hijacking
    defineReactive(obj,key,value){
        this.observer(value); // If the argument passed in is an object, call back the function, which is a recursive function
        
        let dep = new Dep(); // Add a publish and subscribe feature to each attribute
        
        Object.defineProperty(obj,key,{
            get(){
                // When we create watcher, we get the corresponding content and put watcher globally
                Dep.target && dep.addSub(Dep.target);
                return value;
            },
            set: (newVal) = >{
                if(value ! == newVal){this.observer(newVal); // Add the get set method to the new value
                    value = newVal;
                    dep.notify(); // Execute the observer update function}})}}Copy the code

16. Differences, advantages and disadvantages between single-page apps and multi-page apps

A single page application (SPA), colloquially, is an application that has only one home page

  • The browser has to load all the necessary HTML, JS, and CSS at first, which takes a lot of time.
  • All page content is contained in this so-called home page.
  • A single page jump, dynamically loaded by the routing program, only refresh local resources.
  • It is mainly used on PCS.

The main page of a single page is slow to be loaded for the first time: you can install the plug-in required by dynamic lazy loading. Use CDN resources.

SinglePage Web Application (SPA) MultiPage application
composition A home page Multiple complete pages constitute
Resource sharing (CSS, JS) Shared, the browser starts by loading all the necessary HTML, JS, and CSS Not shared, each page has its own CSS, JS
Refresh the way Partial page refresh or change A full page refresh
Url patterns a.com/#/pageone a.com/#/pagetwo a.com/pageone.html a.com/pagetwo.html
Animated transitions Easy to implement, quick switching between page fragments, good user experience Unable to achieve the page switching load slowly, fluency is not enough, the user experience is poor
The data transfer Easy, value transfer between components Depend on URL parameter transfer, cookie, localStorage, etc
Search Engine Optimization (SEO) It requires a separate scheme and is difficult to implement, which is not conducive to SEO retrieval using server-side rendering (SSR) optimization Simple implementation method
The trial scope High requirements of experience, the pursuit of smooth interface applications Ideal for applications that seek high search engine support
Development and maintenance costs Development costs are high, professional frameworks are often needed, and maintenance is relatively easy The development cost is low, but the page repeats the code much, the maintenance is relatively complex

17. What is the difference between vue-router jump and location.href

Use location.href=’/url’ to jump, simple and convenient, but refresh the page;

Use location.href to quickly locate the page div block location.href='#divClass'//
      
Top.location. href redirects to the outermost pageCopy the code

PushState (‘/url’); The server needs to cooperate

18. Please tell me the process of vUE component encapsulation.

  1. To create a template for the component, put the shelf up first, write the style, and consider the basic logic of the component.
  2. Prepare data entry for the component. That is, analyze the logic and determine the data and types in props.
  3. Prepare the data output of the component. That is, do the exposed method (this.$emit) according to the component logic.

19. Vue initialization page flash problem

  • Encountered when loading{{value.name}}Flicker, because that’s what you wrote in the rendering<p>{{value.name}}</p>
  • When loading, you get an empty box with nothing in it, because that’s what you wrote in the rendering<p v-html="value.name"></p>

The solution

The V-Cloak doesn’t need to be added to every TAB, just to the TAB the EL mounts, which is the simplest and most efficient way to do it

//app.vue
<div class="#app" v-cloak>
    <p>{{value.name}}</p>
</div>
//css
[v-cloak] {
    display: none;
}
// This prevents the page from flickering.
Copy the code

But sometimes it doesn’t work for two possible reasons:

  • The display property of the V-cloak is overwritten by a higher layer, so it needs to be raised
[v-cloak] {
    display: none ! important; }Copy the code
  • The style is placed in the CSS file imported by @import (traditional development method) and the style does not work in the CSS file imported by @import at V-Cloak. It can be placed in the CSS file imported by link or in inline style

Knowledge points that are not popular

1. What happens if the child component changes the data in props

  • The changed props data is of the basic type

If you modify a base type, an error is reported

props: {
    num: Number,}created() {
    this.num = 999
  }
Copy the code

  • The changed props data is a reference type
props: {
    item: {
      default: () = >{},}}created() {
    // No error is reported, and the parent data will change
    this.item.name = 'sanxin';
    
    // Will report an error, just as the base type does
    this.item = 'sss'}, copy the codeCopy the code

2. How to customize props

props: {
    num: {
      default: 1.validator: function (value) {
          // If the value is true, the authentication fails and an error is reported
          return [
            1.2.3.4.5].indexOf(value) ! = = -1}}}Copy the code

3. When watch is listening to an object, how to exclude the listening of certain attributes

If params changes, request data again, whether a, B, C, d attribute changes

data() {
    return {
      params: {
        a: 1.b: 2.c: 3.d: 4}}; },watch: {
    params: {
      deep: true.handler() {
        console.log('What property changes perform')}}},Copy the code

But what if I just want to ask again when A, B changes, and not ask again when C, D changes?

mounted() {
  const handler = function(){
    console.log('What property changes perform')}Object.keys(this.params)
    .filter(item1= >! ["c"."d"].includes(item1))// Does not contain c, d attributes
    .forEach(item2= > {
      this.$watch(vm= > vm.params[item2], handler, {
        deep: true
      });
    });
}
Copy the code

5. What is data-V-xxxxx found when reviewing elements

This is the result of using the scoped tag when marking CSS in vue files. To ensure that CSS in files do not interfere with each other, each component is uniquely marked, so a new ‘data-v-xxx’ tag appears every time a Component is introduced

6. How does computed parameter transfer work?

// html
<div>{{ total(3)}}// js
computed: {
    total() {
      return function(n) {
          return n * this.num
         }
    },
}
Copy the code

7. Use of hook of Vue

  • Used in the same component

This is the way we usually use timers

Juejin. Cn/post / 698722…

export default{
  data(){
    timer:null  
  },
  mounted(){
      this.timer = setInterval(() = >{
      // Specific execution content
      console.log('1');
    },1000);
  }
  beforeDestory(){
    clearInterval(this.timer);
    this.timer = null; }}Copy the code

Disadvantages:

  • The timer is not cleared to null after clearInterval.
  • The code to start and clear timers is split in two places, which hurts readability/maintainability, and makes it harder to programmatically clean up what we’ve built, in Big Words.
  • Timer is defined in data. In fact, timer does not require any responsive operation. It is unnecessary to define timer in data, which causes a waste of performance.
Use hooks to listen on the beforeDestroy lifecycle so that the timer is defined only in the lifecycleexport default{
  methods: {fn(){
      const timer = setInterval(() = >{
        // Execute code
        console.log('1');
      },1000);
      this.$once('hook:beforeDestroy'.() = >{
        clearInterval(timer);
        timer = null; })}}}Copy the code

Problem: In background systems, we often set the page cache and do not follow the beforeDestroy life cycle when routes are keep-alive cached. Activated and deactivated are raw hooks

export default {
  data() {
    return{}},mounted() {
    let timer = setInterval(() = > {
      console.log('setInterval')},2000)
    this.$on('hook:activated'.() = > {
      if (timer === null) { // Avoid starting the timer repeatedly
        timer = setInterval(() = > {
          console.log('setInterval')},2000)}})this.$on('hook:deactivated'.() = > {
      clearInterval(timer)
      timer = null$on = $once; $on = $once; $on = $once;Copy the code
  • 7.2 Using Parent and Child Components

/ / if a child component needs to trigger a function of its parent when mounted,

/ / the parent component
<rl-child @childMounted="childMountedHandle"/>
method () {
  childMountedHandle() {
  // do something...}},/ / child component
mounted () {
  this.$emit('childMounted')},Copy the code

Hook can be more convenient:

/ / the parent component
<rl-child @hook:mounted="childMountedHandle"/>
method () {
  childMountedHandle() {
  // do something...}},Copy the code

8. Are provide and inject responsive

Purpose: Used by a parent component to pass data to descendant components

Provide returns data to children in parent components, inject data into children or grandchildren that need to use this data.

// Ancestor component
provide(){
    return {
   // keyName: {name: this.name}, // value is an object that can be used as a reference type
      keyName: this.changeValue // It is also possible to use a function as a value, not this.changevalue ().
   // keyName: 'test' value Cannot be reactive if it is a basic type}},data(){
  return {
    name:'Joe'}},methods: {
    changeValue(){
        this.name = 'Changed name - Li Si'}}// Descendant components
  inject: ['keyName']
  create(){
    console.log(this.keyName) // Change the name - Li Si
}
Copy the code

9.Vue el attribute and $mount priority?

For example, in the following case, which node Vue will render to

new Vue({
  router,
  store,
  el: '#app'.render: h= > h(App)
}).$mount('#ggg')
Copy the code

If el and $mount exist together, el priority > $mount

10. Have you used dynamic instructions and parameters?

<template>
    ...
    <aButton @[someEvent]="handleSomeEvent()" :[someProps]="1000"/ >... </template><script>.data(){
    return{...someEvent: someCondition ? "click" : "dbclick".someProps: someCondition ? "num" : "price"}},methods: {
    handleSomeEvent(){
      // handle some event}}</script>
Copy the code

11. How are the same routing components re-rendered?

Developers often encounter situations where multiple routes resolve to the same Vue component. The problem is that Vue will not re-render shared components by default for performance reasons

const routes = [
  {
    path: "/a".component: MyComponent
  },
  {
    path: "/b".component: MyComponent
  },
];
Copy the code

What if I still want to re-render? You can use keys

<template>
    <router-view :key="$route.path"></router-view>
</template>
Copy the code

12. How to obtain the initial state of a certain data in data?

In development, sometimes you need to calculate the initial state

You can get the initial value by calling this.$options.data().xxx

data() {
    return {
      num: 10
  },
mounted() {
    this.num = 1000
  },
methods: {
    howMuch() {
        // Calculate how much num has increased, which is 1000 - the initial value
        console.log(1000 - this.$options.data().num)
    }
  }
Copy the code

conclusion

Feel good writing, helpful to you, you can share with people around you, the more you share knowledge, do not be stingy

Follow-up update front-end other knowledge summary, please pay attention to me, tidy up, share with you, we learn front-end together