preface

Hello everyone, I’m Lin three hearts, many things have happened in these days (specific is what I would say), these things, frighten me all these years of Vue knowledge out again, if can come to the conclusion that a is a more, I took out my notes, and tried to recall, and finally realize the 50 points (za don’t be too vulgar ah, don’t call the interview, Let’s call it knowledge.)

The glory of gold

1. The advantages of Vue? The downside of Vue?

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

Disadvantages: single page is not good for SEO, do not support IE8 below, the first screen load time is long

2. Why is Vue a progressive framework?

Progressive: colloquial point is, you want to use what you use, we also do not force you. You can use Component or not, and you can use Vuex or not

3. What’s the difference between Vue and React?

Similarities:

  • 1. Virtual DOM is used
  • 2. Componentized development
  • 3. One-way data flow (between parent and child components, it is not recommended that children modify the data handed down by the parent)
  • 4. Both support server-side rendering

Difference:

  • React JSX, Vue template
  • 2. Data changes, React manually (setState), Vue automatically (initialized reactive processing, object.defineProperty)
  • 3.React one-way binding and Vue two-way binding
  • Redux from React, Vuex from Vue

4. What is MVVM? How is it different from MVC?

MVC

  • Model: Is responsible for fetching data from the database
  • View: The place where the data is presented
  • Controller: A place where the user interacts, such as click events, etc
  • Idea: The Controller displays data from the Model on the View

MVVM

  • The VM, or view-Model, does two things to achieve bidirectional binding of data. One is to convert the Model into the View, which is to convert the data passed in the back end into the page that you see. The way to do this is: data binding. The second is to convert [view] into [model], which is to convert the page you see into data at the back end. DOM event listener.
  • Idea: Realize automatic synchronization between View and Model, that is, when the property of Model changes, we do not need to manually operate the Dom element to change the View display, but after changing the property, the corresponding View layer display will automatically change (corresponding to Vue data driven idea)

The difference between

Overall, MVVM is much simpler than MVC, not only simplifying business and interface dependencies, but also solving the problem of frequently updating data without having to manipulate DOM elements with selectors. Because in MVVM, the View is not aware of the Model and the View is not observed by the Model and ViewModel, this low coupling pattern improves code reusability

Is Vue an MVVM framework?

Vue is the MVVM framework, but not exactly MVVM, because MVVM states that models and views cannot communicate directly, whereas Vue’s REF does

5. What’s the difference between Vue and JQuery? Why not use Vue instead of JQuery?

  • 1. JQuery directly operates the DOM, while Vue does not directly operate the DOM. The data of Vue is separate from the view, and Vue only needs to operate the data
  • 2. The DOM operation behavior of jQuery is frequent, while Vue uses the technology of virtual DOM to greatly improve the performance of DOM update
  • 3.Vue does not advocate direct manipulation of the DOM, developers just need to focus most of their efforts on the data level
  • 4.Vue integrates some libraries, which greatly improves the development efficiency, such as Vuex, Router, etc

6. Who wrote Vue? Say its name out loud!!

His name is: squid west

Eternal diamond

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

Data is a single function because a component can be called multiple times, and each call will execute the data function and return a new data object, thus avoiding data contamination between calls.

8. What Vue modifiers have you used?

Check out my article on the 13 Vue modifiers that interviewers love to ask

9. What internal Vue commands have you used?

10. What are the ways to pass values between components?

  • The parent component passes values to the child component, and the child component uses thempropsTo receive
  • The child component passes values to the parent component, which the child component uses$emit + eventPass the value to the parent component
  • Component$parentand$childrenGet the parent component instance and the child component instance, and then get the data
  • use$attrsand$listenersIn the secondary encapsulation of some components can be easily passed values, such as A->B->C
  • use$refsGet the component instance, and hence the data
  • useVuexPerform state management
  • useeventBusTriggers events across components to pass data
  • useprovideandinjectThe official advice is not to use this. I’m lookingElementUISource code is found to be heavily used
  • Use the browser local cache, for examplelocalStorage

11. What are the routing modes? What difference does it make?

  • Hash mode: Passed# no.The following content changes are triggeredhashchangeEvent to implement route switchover
  • History mode: PassedpushStateandreplaceStateThe URL switch is triggeredpopstateEvent to implement route switchover. The back-end needs to work together

12. How to set dynamic class and dynamic style?

  • Dynamic class objects:<div :class="{ 'is-active': true, 'red': isRed }"></div>
  • Dynamic class arrays:<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’s the difference between v-if and V-show?

  • 1.v-ifBy controlling the deletion and generation of DOM elements, explicit and implicit are realized. Each explicit and implicit will make the component run through the life cycle again, because explicit and implicit determine the generation and destruction of the component
  • 2.v-showThe CSS style of dom elements is controlled to achieve explicit and implicit, not destroyed
  • 3. Frequent or large number of explicit or implicit usev-show, otherwise usev-if

14. What is the difference between computed and watch?

  • 1.computedIs to rely on existing variables to calculate a target variable, most of the timeMultiple variablesLet’s get together and figure it outA variableAnd,computedwithCaching mechanisms, it will directly read the cache for reuse if the dependency value remains unchanged.computedCannot beAsynchronous operations
  • 2.watchIs to listen for a change in a variable and execute the corresponding callback function, usuallyA variableDetermines the change ofMultiple variablesThe change,watchCan be doneAsynchronous operations
  • 3. In generalcomputedisFor one more.watchisMore than a pair of

15. What is the life cycle of Vue?

16. Why are V-if and V-for not recommended on the same label?

In Vue2, v-for has a higher priority than V-if. Let’s look at an example

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

The above method is written as v-for and V-if exist at the same time. First, all 7 elements are traversed, and then each one is judged to be 3, and 3 is hidden. The disadvantage of this method is that useless 3 nodes are rendered and useless DOM operations are added.

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

computed() {
    list() {
        return [1.2.3.4.5.6.7].filter(item= >item ! = =3)}}Copy the code

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

  • State: A data structure that defines the State of the application, where you can set the default initial State.
  • Getters: To allow a component to get data from a Store, the mapGetters helper function simply maps getters in a Store to locally computed properties.
  • Mutation: is the only method to change the state in store and must be a synchronous function.
  • Action: Used for submitting mutations rather than directly changing state and can include any asynchronous operation.
  • Module: Allows a single Store to be split into multiple stores and stored in a single state tree.

The ultimate star yao

18. What should be done with the data that does not need to be responsive?

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 consumes a lot of performance.

// Method 1: define data outside of data
data () {
    this.list1 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list2 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list3 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list4 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    this.list5 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
    return{}}// Freeze ();
data () {
    return {
        list1: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list2: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list3: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list4: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
        list5: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}),
    }
 }
Copy the code

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

When we listen to a basic data type:

watch: {
    value () {
        // do something}}Copy the code

When we listen for a reference data type:

watch: {
    obj: {
       handler () { // Perform the callback
           // do something
       },
       deep: true.// Whether to perform deep listening
       immediate: true // Whether to execute the handler function initially}}Copy the code

20. Parent-child component lifecycle sequence

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

21. The object cannot update the view with a new property. The object cannot update the view with a deleted property. How to do?

  • The reason:Object.definePropertyThere is no property hijacking of the object’s new properties
  • Object new properties cannot update views: UsedVue.$set(obj, key, value), a component ofthis.$set(obj, key, value)
  • Unable to update view by deleting properties: UsedVue.$delete(obj, key), a component ofthis.$delete(obj, key)

22. {arr[index] = XXX} Why is that? How to do?

  • Cause: Vue did not perform on the arrayObject.definePropertySo arr[index] = XXX is not able to update the view
  • Using the array splice method,arr.splice(index, 1, item)
  • useVue.$set(arr, index, value)

23. Custom instructions

I recommend this article for eight very useful Vue custom directives

24. How does the slot work and how does it work?

I suggest this article “Vue source learning” do you really know how slots are “inserted”

25. Why is it not recommended to use index as key? Why is it not recommended to use random number as 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 execute list.unshift({name: 'xiao Lin'.id: '122'}) render as <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><div key="0"Xiao Ming > </div> 
      
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 execute 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><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>As can be seen, the original three are unchanged, but the addition of xiaolin this person, this is the most ideal resultCopy the code

Use index and use random number are the same, random number is changing every time, do not be specific, very cheating women’s feelings of men, also very consumption of performance, so, refused to cheat women’s feelings of men, choose honest people

26. What’s the use of nextTick?

Here’s an example, in vue:

this.name = 'Lin SAN Xin'
this.age = 18
this.gender = 'male'
Copy the code

We’ve changed three variables, so the question is, is the DOM updated every time we change it? No, Vue uses an asynchronous update strategy. Generally speaking, the view will be updated once for multiple changes within the same event loop, so as to save performance

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

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

name: 'xiao Lin'

this.name = 'Lin SAN Xin'
console.log(this.$refs.testDiv.innerHTML) // What is this
Copy the code

Vue is an asynchronous update, so when the data is updated, the view is not updated, so you still get the old view data, so what do you do to get the latest view data?

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

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

  • SSRIt’s server-side rendering
  • Based on thenodejs serveService environment development, allhtmlThe code is rendered on the server side
  • The data is returned to the front end, which then “activates” it to become HTML code recognized by the browser
  • SSRThe first loading 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, because the data has to be parsed, the crawler will not wait for your data to be loaded, so in fact, the SEO experience of the VUE project is not very good

Most of the king

28. How is the Vue response implemented?

The whole idea is data hijacking + observer

Objects are internally hijacked (only existing properties are hijacked) using object.defineProperty via defineReactive methods, and arrays are overridden by array methods. When the page uses the corresponding property, each property has its own DEP property, which holds the watcher that it depends on (dependency collection). When the property changes, the corresponding watcher is notified to update (dispatch updates).

For more details on the process, I recommend reading my Vue source code parsing 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
    }
})

Copy the code

29. Why hijack only objects but override methods on arrays?

Since an object has only a few dozen properties at most, it is not much to intercept, but an array may have hundreds or thousands of properties, which is very performance consuming. Therefore, overriding the array prototype method directly is a performance saving solution

30. How does Vue compile templates?

Because this may be a long story, so:

I recommend to see this “Vue source learning (2)” you do not know – template compilation principles

31. How do Vue’s computed and Watch work?

Because this may be a long story, so:

I recommend this “Vue source learning (4)” to write a everyone to understand the computed, Watch principle

32. How does vue. set work?

function set(target, key, val) {
    // Check whether it is an array
    if (Array.isArray(target)) {
        // Judge who is older and who is younger
        target.length = Math.max(target.length, key)
        / / execution splice
        target.splice(key, 1, val)
        return val
    }

    const ob = target.__ob__

    // If the object does not have a non-reactive object, set it directly and return it
    if (key intarget && ! (keyintarget.prototype) || ! ob) { target[key] = valreturn val
    }

    // Otherwise, add a new attribute and process it responsively
    defineReactive(target, key, val)
    return val
}
Copy the code

33. How does vue. delete work?

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

    const ob = target.__ob__

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


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

    // If it is a reactive object, return it
    if(! ob)return
    // If yes, notify the view to update after the deletion
    ob.dep.notify()
}
Copy the code

34. How does nextTick work?

let callbacks = []; // The callback function
let pending = false;
function flushCallbacks() {
  pending = false; // Restore flag to false
  // Execute the callbacks in sequence
  for (let i = 0; i < callbacks.length; i++) { callbacks[i](); }}let timerFunc; // Start with a microtask and gracefully degrade the priority to implement asynchronous refresh
if (typeof Promise! = ="undefined") {
  // If promise is supported
  const p = Promise.resolve();
  timerFunc = () = > {
    p.then(flushCallbacks);
  };
} else if (typeofMutationObserver ! = ="undefined") {
  // MutationObserver is an asynchronous method that listens for dom changes
  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 (typeofsetImmediate ! = ="undefined") {
  // If neither of the preceding supports setImmediate
  timerFunc = () = > {
    setImmediate(flushCallbacks);
  };
} else {
  // The last degradation is to use setTimeout
  timerFunc = () = > {
    setTimeout(flushCallbacks, 0);
  };
}

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

35. What’s the use of a key? What about the Diff algorithm?

Why not use index as key in Vue? (Diff algorithm detailed)

I can’t tell it as well as he can

Obscure knowledge

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

  • The props data changed is the basic type

If the basic type is modified, an error is reported

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

  • The props data changed is a reference type
props: {
    item: {
      default: () = >{},}}created() {
    // No error is reported, and the parent data changes accordingly
    this.item.name = 'sanxin';
    
    // An error will be reported, just as an error will be reported for the base type
    this.item = 'sss'
  },
Copy the code

37. How to customize validation for props

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

38. What is the use of the Immediate attribute on watch?

For example, if we request the data once when created, and request the data when the search value changes, we would write:

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

You can write this completely with immediate. When it is true, it is initially executed

watch: {
  searchInputValue: {handler: 'getList'.immediate: true}}Copy the code

39. When watch listens to an object, how to exclude certain properties from listening

If params changes, the data will be rerequested, whether the 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; }},}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() {
    Object.keys(this.params)
      .filter((_) = >! ["c"."d"].includes(_)) // Exclude listening for 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; }},}Copy the code

40. What is data-V-xxXXX when reviewing an element?

This is caused by using the scoped tag when marking CSS in a vue file. To ensure that the CSS in each file does not interact with each other, each component is marked uniquely, so that each component is introduced with a new ‘data-v-xxx’ tag

41. For computed, how do I implement parameters transmission?

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

Copy the code

42. Use of Vue’s hook

  • Used in the same component

This is how we usually use timers

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

The problem with this approach is that you need to define an additional timer variable globally. You can use hook to do this:

export default{
  methods: {fn(){
      const timer = setInterval(() = >{
        // Execute the code
        console.log('1');
      },1000);
      this.$once('hook:beforeDestroy'.() = >{
        clearInterval(timer);
        timer = null; })}}}Copy the code
  • 7.2 Use of parent and child Components

If a child component wants to fire a function of its parent component when mounted, it would normally write:

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

It is more convenient to use hook:

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

43. Are provide and inject responsive?

// The ancestor component
provide(){
    return {
   // keyName: {name: this.name}, // value is an object to implement the response, that is, the reference type
      keyName: this.changeValue // This can also be done by using a function. [Note that the function is a value, not this.changevalue ()]
   // keyName: 'test' value If it is a basic type, the response cannot be implemented}},data(){
  return {
	name:'Joe'}},methods: {
  	changeValue(){
  		this.name = 'Changed name - Lee Si'}}// The descendant component
  inject: ['keyName']
  create(){
	console.log(this.keyName) // The new name is Lisi
}
Copy the code

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')
Copy the code

Here is an official chart showing that when el and $mount exist together, the el priority is > $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>
Copy the code

46. How can the same routing component be rerendered?

Developers often encounter situations where multiple routes resolve to the same Vue component. The problem is that Vue for performance reasons by default shared components will not be rerendered and if you try to switch between routes that use the same component nothing will change.

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

What if I still want to rerender? You can use keys

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

47. Customize the V-Model

By default, v-Model is the syntactic sugar on the @Input event listener and the :value attribute. However, you can specify a model property in your Vue component to define what event and value properties to use — great!

export default: {
  model: {
    event: 'change'.prop: 'checked'}}Copy the code

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

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

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

49. Why is v-for and V-IF not recommended

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

The above method is written as v-for and V-if exist at the same time. First, all 7 elements are traversed, and then each one is judged to be 3, and 3 is hidden. The disadvantage of this method is that useless 3 nodes are rendered and useless DOM operations are added.

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

computed() {
    list() {
        return [1.2.3.4.5.6.7].filter(item= >item ! = =3)}}Copy the code

50. Which is better, methods or computed?

<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

Computed is better because computed has caching. For example, if index changes from 0 to 1, the view will be updated and methods will be executed again, but computed will not, because the two variables on which Computed depends, num and price, will not change.