“Self test” stay up late to summarize 50 Vue knowledge points, all of which will make you God!!!

Time:2021-10-27

preface

Hello everyone, I’m Lin Sanxin. A lot of things have happened these days (I won’t say what’s specific). These things have scared me to treasure my collection these yearsVue knowledge pointsI took out my notes and tried my best to recall them. Finally, I realized these 50Knowledge points(let’s not be too vulgar. It’s not an interview question, but a knowledge point)

Glory gold

1. What are the advantages of Vue? The disadvantages of Vue?

Advantages: progressive, componentized, lightweight, virtual DOM, responsive, single page routing, separation of data and view

Disadvantages: single page is not conducive to SEO, does not support IE8 or below, and takes a long time to load the first screen

2. Why is Vue a progressive framework?

Progressive: Generally speaking, you can use whatever you want. We don’t force you. If you want to use component, you can use it without using it. If you want to use vuex, you can use it without using it

3. What are the similarities and differences between Vue and react?

Similarities:

  • 1. All use virtual dom
  • 2. Component development
  • 3. Both are one-way data flows (between parent and child components, it is not recommended to modify the data passed down from the parent)
  • 4. Both support server-side rendering

difference:

  • 1. JSX of react and template of Vue
  • 2. Data change, react manual (setstate), Vue automatic (initialization, responsive processing, object. Defineproperty)
  • 3. React one-way binding and Vue two-way binding
  • 4. Redux of react and vuex of Vue

4. What is MVVM? What’s the difference between and MVC?

MVC

  • Model: responsible for fetching data from the database
  • View: the place responsible for displaying data
  • Controller: where users interact, such as click events, etc
  • Idea: the controller displays the data of the model on the view

MVVM

  • VM: that is, view model does two things to achieve two-way binding of data. One is to convert the [model] into [view], that is, the data transmitted from the back end into the page you see. The implementation method is: data binding. The second is to convert view into model, that is, the page you see into back-end data. The implementation method is: DOM event listening.
  • Idea: it realizes the automatic synchronization between view and model, that is, when the attributes of model are changed, we no longer need to manually operate DOM elements to change the display of view, but the display of view layer corresponding to the attribute will change automatically after changing the attribute (corresponding to Vue data-driven idea)

difference

On the whole, MVVM is much simpler than MVC. It not only simplifies the dependence on business and interface, but also solves the problem of frequent data updates. There is no need to operate DOM elements with selectors. Because in MVVM, the view does not know the existence of the model, and the model and ViewModel do not observe the view, this low coupling mode improves the reusability of the code

Is Vue an MVVM framework?

Vue is an MVVM framework, but it does not strictly comply with MVVM, because MVVM stipulates that model and view cannot communicate directly, and Vue’srefYou can do that

5. What is the difference between Vue and jQuery? Why give up jQuery and use Vue?

  • 1. JQuery operates DOM directly, Vue does not operate DOM directly, Vue’s data and view are separated, and Vue only needs to operate data
  • 2. In the scene of frequent DOM operation, jQuery operates DOM frequently, and Vue uses virtual DOM technology to greatly improve the performance when updating dom
  • 3. Vue does not advocate direct operation of DOM, and developers only need to focus most of their energy on the data level
  • 4. Some libraries integrated by Vue greatly improve development efficiency, such as vuex, router, etc

6. Who is the author of Vue? Say its name out loud!!!

His name is squid West

Eternal diamond

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

dataThe reason why there is only one function is that a component may call multiple times, and each call will be executedData functionAnd return a new data object. In this way, you can avoid the conflict between multiple callsData pollution

8. Which Vue modifiers have been used?

You can read my article“Invincible” 13 Vue modifiers that interviewers like to ask

9. What Vue internal instructions have been used?

10. What are the value transfer methods between components?

  • The parent component passes the value to the child component, and the child component uses itpropsReceive
  • The child component passes the value to the parent component, which is used by the child component$emit + EventPass value to parent component
  • Can be used in components$parentand$childrenGet the parent component instance and child component instance, and then get the data
  • use$attrsand$listeners, it is convenient to transfer values when re encapsulating some components, such as a – > b – > C
  • use$refsGet the component instance, and then get the data
  • useVuexConduct status management
  • useeventBusTrigger events across components to transfer data
  • useprovideandinject, the authorities advise us not to use this. I’m watchingElementUIFound extensive use of source code
  • Use browser local caching, for examplelocalStorage

    11. What are the routing modes? What’s the difference?

  • Hash mode: Pass#NumberThe change of the following content triggershashchangeEvent to realize route switching
  • History mode: throughpushStateandreplaceStateSwitch URL, triggerpopstateEvent to realize route switching, which requires back-end cooperation

    12. How to set dynamic class and dynamic style?

  • Dynamic class object:<div :class="{ 'is-active': true, 'red': isRed }"></div>
  • Dynamic class array:<div :class="['is-active', isRed ? 'red' : '' ]"></div>
  • Dynamic style object:<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?

  • 1.v-ifExplicit and implicit are realized by controlling the deletion and generation of DOM elements. Each explicit and implicit will make the component run through the life cycle again, because explicit and implicit determines the generation and destruction of components
  • 2.v-showThis is achieved by controlling the CSS style of DOM elements, which will not be destroyed
  • 3. Frequent or large number of explicit and implicit usev-show, otherwise usev-if

    14. What is the difference between computed and watch?

  • 1.computedIt depends on the existing variables to calculate a target variable. In most cases, it isMultiple variablesTogether, calculateA variable, andcomputedhaveCaching mechanism, when the dependency value remains unchanged, it will directly read the cache for reuse,computedCannot proceedAsynchronous operation
  • 2.watchIs to monitor the change of a variable and execute the corresponding callback function, usuallyA variableChange decisionMultiple variablesChanges in,watchCan proceedAsynchronous operation
  • 3. The simple note is: generallycomputedyesMany to onewatchyesOne to many

    15. Vue’s life cycle, talk about it?

    16. Why are V-IF and V-for not recommended to use the same label?

    In vue2,v-forPriority is higher thanv-ifYes, let’s take an example

    <div v-for="item in [1, 2, 3, 4, 5, 6, 7]" v-if="item !== 3">
      {{item}}
    </div>

    The writing above isv-forandv-ifAt the same time, it will traverse all seven elements, then judge whether they are 3, and hide 3. The disadvantage is that it renders useless 3 nodes and adds useless DOM operations. It is recommended to use computed to solve this problem:

    <div v-for="item in list">
      {{item}}
    </div>
    
    computed() {
      list() {
          return [1, 2, 3, 4, 5, 6, 7].filter(item => item !== 3)
      }
    }

    17. What are the attributes of vuex? What’s the use?

  • State: defines the data structure of the application state. You can set the default initial state here.
  • Getter: allows components to obtain data from the store. The mapgetters auxiliary function only maps getters in the store to local calculation properties.
  • Mutation: is the only way to change the state in the store and must be a synchronization function.
  • Action: used to submit a mutation instead of directly changing the state. It can contain any asynchronous operation.
  • Module: allows you to split a single store into multiple stores and save them in a single state tree at the same time.

    Supreme star shine

18. What should I do with data that does not require responsiveness?

In our Vue development, there will be some data that will be available from beginning to endNever changed, thisDead data, sinceNo change, that’s itThere is no need to respond to himOtherwise, it will only do some useless work and consume performance, such as some dead drop-down boxes and dead table data, which have a large amount of dataDead data, if they are all processed responsively, it will consume a lot of performance.

//Method 1: define data outside data
data () {
    this.list1 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list2 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list3 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list4 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list5 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    return {}
 }
    
//Method 2: object. Freeze()
data () {
    return {
        list1: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list2: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list3: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list4: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list5: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
    }
 }

19. What are the attributes of watch and what are their uses?

When we listen to a basic data type:

watch: {
    value () {
        // do something
    }
}

When we listen for a reference data type:

watch: {
    obj: {
       Handler() {// execute callback
           // do something
       },
       Deep: true, // whether to perform deep listening
       Immediate: true // whether to initially execute the handler function
    }
}

20. Parent child component life cycle sequence

Parent beforecreate – > parent created – > parent beforemount – > child beforecreate – > child created – > child beforemount – > child mounted – > parent mounted

21. The view cannot be updated when the new attribute of the object is deleted, and the view cannot be updated when the attribute is deleted. Why? What should I do?

  • reason:Object.definePropertyNo property hijacking was performed on the new property of the object
  • Cannot update view using new properties of object:Vue.$set(obj, key, value), in componentthis.$set(obj, key, value)
  • Cannot update view by deleting attribute:Vue.$delete(obj, key), in componentthis.$delete(obj, key)

    22. What if arr [index] = XXX cannot update the view directly? Why? What should I do?

  • Cause: Vue did not modify the arrayObject.definePropertyThe properties of are hijacked, so the view cannot be updated directly when arr [index] = XXX
  • Using the splice method of the array,arr.splice(index, 1, item)
  • useVue.$set(arr, index, value)

    23. Custom instructions

    I suggest reading this article8 very practical Vue custom instructions

    24. Use and principle of slot?

    I suggest reading this article“Vue source code learning” do you really know how slot slot is “inserted”

    25. Why not use index as key and random number as key?

    for instance:

    <div v-for="(item, index) in list" :key="index">{{item.name}}</div>
    
    list: [
      {Name: 'Xiaoming', ID: '123'},
      {Name: 'Xiaohong', ID: '124'},
      {Name: 'Xiaohua', ID: '125'}
    ]
    
    Render as
    < div key = "0" > Xiao Ming < / div >
    < div key = "1" > Xiao Hong < / div >
    < div key = "2" > floret < / div >
    
    Now I execute list. Unshift ({Name: 'Kobayashi', ID: '122'})
    
    Render as
    < div key = "0" > Kobayashi < / div >
    < div key = "1" > Xiao Ming < / div >
    < div key = "2" > Xiao Hong < / div >
    < div key = "3" > floret < / div >
    
    
    Comparison between old and new
    
    < div key = "0" > Xiao Ming < / div >  < div key = "0" > Kobayashi < / div >
    < div key = "1" > Xiao Hong < / div >  < div key = "1" > Xiao Ming < / div >
    < div key = "2" > floret < / div >  < div key = "2" > Xiao Hong < / div >
                           < div key = "3" > floret < / div >
    
    It can be seen that if the index is used as the key, the original three items are updated and florets are added. Although the rendering purpose is achieved, the performance is lost
    
    现在我们使用id来做key,Render as
    
    < div key = "123" > Xiao Ming < / div >
    < div key = "124" > Xiao Hong < / div >
    < div key = "125" > floret < / div >
    
    Now I execute list. Unshift ({Name: 'Kobayashi', ID: '122'}),Render as
    
    < div key = "122" > Kobayashi < / div >
    < div key = "123" > Xiao Ming < / div >
    < div key = "124" > Xiao Hong < / div >
    < div key = "125" > floret < / div >
    
    Comparison between old and new
    
                             < div key = "122" > Kobayashi < / div >
    < div key = "123" > Xiao Ming < / div >  < div key = "123" > Xiao Ming < / div >
    < div key = "124" > Xiao Hong < / div >  < div key = "124" > Xiao Hong < / div >
    < div key = "125" > floret < / div >  < div key = "125" > floret < / div >
    
    It can be seen that the original three items remain unchanged, but Kobayashi is added, which is the most ideal result

    useindexAnd userandom numberThe same is true,random numberIt’s changing every time. It’s hard to be specificscumbag, it also consumes performance, so refusescumbag, selecthonest person

    26. What’s the use of nexttick?

    For example, in Vue:

    This. Name = 'Lin Sanxin'
    this.age = 18
    This. Gender = 'male'

    We modified three variables. The question arises. Is the DOM updated every time we modify it? No, Vue usesAsynchronous updateYour strategy, more generally,Within the same event cycleMultiple modifications willunifiedOnceView update, so as to save performance

If you understand the above, you should also understand the following examples:

<div ref="testDiv">{{name}}</div>

Name: 'Kobayashi'

This. Name = 'Lin Sanxin'
Console.log (this. $refs. Testdiv. InnerHTML) // what's here

The answer is “Kobayashi”. As mentioned earlier, Vue isAsynchronous updateTherefore, once the data is updated, the view has not been updated, so what you get is the old view data of the last time. What do you want to do to get the latest view data?

This. Name = 'Lin Sanxin'
this.$nextTick(() => {
    Console.log (this. $refs. Testdiv. InnerHTML) // Lin Sanxin
})

27. What is Vue’s SSR? What are the benefits?

  • SSRServer rendering
  • be based onnodejs serveService environment development, allhtmlThe code is rendered on the server side
  • The data is returned to the front end, and then the front end is “activated”, which can become the HTML code recognized by the browser
  • SSRThe first load is faster, with better user experience and better SEO optimization, because the crawler can see the content of the whole page. If it is a Vue project, the data needs to be parsed, so the crawler will not wait for your data to be loaded. In fact, the SEO experience of Vue project is not very good

The strongest King

28. How is Vue responsive implemented?

The overall idea is data hijacking + observer mode

Object internal pass defineReactiveMethod, usingObject.definePropertyHijack attributes (only existing attributes will be hijacked), and the array is realized by rewriting the array method. When the page uses corresponding attributes, each attribute has its own dep Property to store the data it depends on watcher(dependent Collection). When the attribute changes, it will notify its corresponding user watcherTo update (distribute updates).

To learn more about the process, I suggest reading myVue source code analysis series

const { arrayMethods } = require('./array')

class Observer {
    constructor(value) {
        Object.defineProperty(value, '__ob__', {
            value: this,
            enumerable: false,
            writable: true,
            configurable: true
        })
        if(Array.isArray(value)) {
            value.__proto__ = arrayMethods
            this.observeArray(value)
        } else {
            this.walk(value)
        }
    }

    walk(data) {
        let keys = Object.keys(data)
        for(let i = 0; i < keys.length; i++) {
            const key = keys[i]
            const value = data[key]
            defineReactive(data, key, value)
        }
    }

    observeArray(items) {
        for(let i = 0; i < items.length; i++) {
            observe(items[i])
        }
    }
}

function defineReactive(data, key, value) {
    const childOb = observe(value)

    const dep = new Dep()

    Object.defineProperty(data, key, {
        get() {
            Console.log ('Get value ')
            if (Dep.target) {
                dep.depend()

                if (childOb) {
                    childOb.dep.depend()

                    if (Array.isArray(value)) {
                        dependArray(value)
                    }
                }
            }
            return value
        },
        set(newVal) {
            if (newVal === value) return
            observe(newVal)
            value = newVal
            dep.notify()
        }
    })
}

function observe(value) {
    if (Object.prototype.toString.call(value) === '[object Object]' || Array.isArray(value)) {
        return new Observer(value)
    }
}

function dependArray(value) {
    for(let e, i = 0, l = value.length; i < l; i++) {
        e = value[i]

        e && e.__ob__ && e.__ob__.dep.depend()

        if (Array.isArray(e)) {
            dependArray(e)
        }
    }
}

// array.js
const arrayProto = Array.prototype

const arrayMethods = Object.create(arrayProto)

const methodsToPatch = [
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'reverse',
    'sort'
]

methodsToPatch.forEach(method => {
    arrayMethods[method] = function (...args) {
        const result = arrayProto[method].apply(this, args)

        const ob = this.__ob__

        var inserted

        switch (method) {
            case 'push':
            case 'unshift':
                inserted = args
                break;
            case 'splice':
                inserted = args.slice(2)
            default:
                break;
        }

        if (inserted) ob.observeArray(inserted)

        ob.dep.notify()

        return result
    }
})

29. Why only hijack objects and override arrays?

Because there are at most dozens of attributes of an object, the number of interceptions is small, but the array may have hundreds and thousands of items, which is very performance-consuming. Therefore, directly rewriting the method on the array prototype is a performance-saving scheme

30. Vue’s template compilation principle?

Because this question may be long, so:

I suggest you read this article“Vue source code learning (II)” what you don’t know – the principle of template compilation

31. Vue’s principle of computed and watch?

Because this question may be long, so:

I suggest you read this article“Vue source code learning (IV)” determined to write a calculated, watch principle that everyone can understand

32. Principle of vue.set method?

function set(target, key, val) {
    //Determine whether it is an array
    if (Array.isArray(target)) {
        //Judge who is big and who is small
        target.length = Math.max(target.length, key)
        //Execute splice
        target.splice(key, 1, val)
        return val
    }

    const ob = target.__ob__

    //If this object is not a responsive object, set it directly and return it
    if (key in target && !(key in target.prototype) || !ob) {
        target[key] = val
        return val
    }

    //Otherwise, add a new attribute and handle it responsively
    defineReactive(target, key, val)
    return val
}

33. Principle of vue.delete method?

function del (target, key) {
    //Determine whether it is an array
    if (Array.isArray(target)) {
        //Execute splice
        target.splice(key, 1)
        return
    }

    const ob = target.__ob__

    //The object itself does not have this property and returns directly
    if (!(key in target)) return


    //Otherwise, delete this property
    delete target[key]

    //Judge whether it is a responsive object. If not, return it directly
    if (!ob) return
    //If yes, notify the view update after deletion
    ob.dep.notify()
}

34. How does nexttick work?

let callbacks = []; // Callback function
let pending = false;
function flushCallbacks() {
  pending = false; // Restore flag to false
  //Execute callbacks in turn
  for (let i = 0; i < callbacks.length; i++) {
    callbacks[i]();
  }
}
let timerFunc; // Firstly, the asynchronous refresh is realized by using micro tasks and graceful degradation of priority
if (typeof Promise !== "undefined") {
  //If promise is supported
  const p = Promise.resolve();
  timerFunc = () => {
    p.then(flushCallbacks);
  };
} else if (typeof MutationObserver !== "undefined") {
  //Mutationobserver is mainly used to listen for DOM changes. It is also an asynchronous method
  let counter = 1;
  const observer = new MutationObserver(flushCallbacks);
  const textNode = document.createTextNode(String(counter));
  observer.observe(textNode, {
    characterData: true,
  });
  timerFunc = () => {
    counter = (counter + 1) % 2;
    textNode.data = String(counter);
  };
} else if (typeof setImmediate !== "undefined") {
  //If the previous judgment is not supported, setimmediate
  timerFunc = () => {
    setImmediate(flushCallbacks);
  };
} else {
  //Finally, setTimeout is adopted for demotion
  timerFunc = () => {
    setTimeout(flushCallbacks, 0);
  };
}

export function nextTick(cb) {
  callbacks.push(cb);
  if (!pending) {
    pending = true;
    timerFunc();
  }
}

35. What’s the use of key? Talk about diff algorithm?

Read this article directly:Why not use index as a key in Vue? (detailed explanation of diff algorithm)

I’m not as good as him

Unpopular knowledge points

36. What happens if a sub component changes the data in props

  • The changed props data is the basic type

    If the basic type is modified, an error will be reported

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

  • The changed props data is a reference type

    props: {
      item: {
        default: () => ({}),
      }
    }
    created() {
      //No error is reported, and the parent data will change accordingly
      this.item.name = 'sanxin';
      
      //An error will be reported, which is the same as that of the basic type
      this.item = 'sss'
    },

37. How does props customize validation

props: {
    num: {
      default: 1,
      validator: function (value) {
          //If the return value is true, the verification fails and an error is reported
          return [
            1, 2, 3, 4, 5
          ].indexOf(value) !== -1
    }
    }
  }

38. What is the use of the immediate attribute of watch?

For example, you need to request data once when you create, and when the search value changes, you also need to request data. We will write this:

created(){
  this.getList()
},
watch: {
  searchInputValue(){
    this.getList()
  }
}

useimmediateIt can be written like this when it’strueIs initially executed once

watch: {
  searchInputValue:{
    handler: 'getList',
    immediate: true
  }
}

39. How to exclude the listening of some attributes when watch listens to an object

The following code is to re request data when params changes, whether a, B, C or D attributes change

data() {
    return {
      params: {
        a: 1,
        b: 2,
        c: 3,
        d: 4
      },
    };
  },
watch: {
    params: {
      deep: true,
      handler() {
        this.getList;
      },
    },
  }

But what if I just want to re request when a and B change and not re request when C and d change?

mounted() {
    Object.keys(this.params)
      . filter (() = >! ["C", "d"]. Includes ()) // exclude listening to C, D attributes
      .forEach((_) => {
        this.$watch((vm) => vm.params[_], handler, {
          deep: true,
        });
      });
  },
data() {
    return {
      params: {
        a: 1,
        b: 2,
        c: 3,
        d: 4
      },
    };
  },
watch: {
    params: {
      deep: true,
      handler() {
        this.getList;
      },
    },
  }

40. Data-v-xxxxx is found when reviewing the element. What is this?

This is generated by using the scoped tag when marking CSS in Vue files. To ensure that CSS in each file does not affect each other, each component is uniquely marked. Therefore, a new ‘data-v-xxx’ tag will appear every time a component is introduced

41. How does computed implement parameter transfer?

// html
<div>{{ total(3) }}

// js
computed: {
    total() {
      return function(n) {
          return n * this.num
         }
    },
  }

42. Use of Vue’s hook

  • Used in the same component

    This is the way we often use timers

    export default{
    data(){
      timer:null  
    },
    mounted(){
        this.timer = setInterval(()=>{
        //Specific implementation contents
        console.log('1');
      },1000);
    }
    beforeDestory(){
      clearInterval(this.timer);
      this.timer = null;
    }
    }

    The bad thing about the above method is that you have to define a timer variable globally. You can use hook to do this:

    export default{
    methods:{
      fn(){
        let timer = setInterval(()=>{
          //Specific execution code
          console.log('1');
        },1000);
        this.$once('hook:beforeDestroy',()=>{
          clearInterval(timer);
          timer = null;
        })
      }
    }
    }
  • 7.2 use of parent-child components

    If the child component needs to trigger a function of the parent component when mounted, it will be written as follows:

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

    It is more convenient to use hook:

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

43. Are provide and inject responsive?

//Ancestor component
provide(){
    return {
   //Keyname: {Name: this. Name}, // value is an object to implement a response, that is, a reference type
      Keyname: this. Changevalue // you can also use a function [note that the function is used as value instead of this. Changevalue()]
   //Keyname: 'test' value if it is a basic type, the response type cannot be implemented
    }
  },
data(){
  return {
    Name: 'Zhang San'
}
  },
  methods: {
      changeValue(){
          This. Name = 'changed name - Li Si'
      }
  }  
  
  //Descendant component
  inject:['keyName']
  create(){
    Console.log (this. Keyname) // changed name - Li Si
}

44. Vue’s El attribute and $mount priority?

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

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

This is an official picture, as you can seeeland$mountWhen both exist,El priority > $mount

45. Have dynamic instructions and parameters been used?

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

46. How to re render the same routing components?

Developers often encounter situations where multiple routes resolve to the same Vue component. The problem is that Vue, for performance reasons, shared components will not be re rendered by default. If you try to switch between routes using the same components, nothing will change.

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

What if you still want to re render? have access tokey

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

47. Custom V-model

By default, V-model is the syntax sugar on the @ input event listener and the: value attribute. However, you can specify a model attribute in your Vue component to define what event and value attributes to use – great!

export default: {
  model: {
    event: 'change',
    prop: 'checked'  
  }
}

48. How to get the initial state of a data in data?

In development, it is sometimes necessary to calculate the initial state. for example

data() {
    return {
      num: 10
  },
mounted() {
    this.num = 1000
  },
methods: {
    howMuch() {
        //Calculate how much num has increased, that is, 1000 - the initial value
        //You can get the initial value through this. $options. Data(). XXX
        console.log(1000 - this.$options.data().num)
    }
  }

49. Why not suggest that V-for and V-IF exist at the same time

<div v-for="item in [1, 2, 3, 4, 5, 6, 7]" v-if="item !== 3">
  {{item}}
</div>

The above method is that V-for and V-IF exist at the same time. We will traverse all seven elements first, then judge whether they are 3 and hide them. The disadvantage is that useless 3 nodes are rendered and useless DOM operations are added. It is recommended to use computed to solve this problem:

<div v-for="item in list">
  {{item}}
</div>

computed() {
  list() {
      return [1, 2, 3, 4, 5, 6, 7].filter(item => item !== 3)
  }
}

50. When calculating variables, which is better, methods or calculated?

<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
    }
  }

computedIt will be better because computed will havecache。 For example, if the index changes from 0 to 1, the view update will be triggered. At this time, the methods will be executed again, but computed will not, because the two variables num and price that computed depends on remain unchanged.

epilogue

If you think this article is of little help to you, give a praise and encourage Lin Sanxin, ha ha.
If you want to fish, look at my personal data, add me, I’ll pull you in, regular meetings, mock interviews, and answer questions