Data and data in prop are available when created.

Computed attributes execute code only when used in Mounted or DOM.

Finally, there’s Mouted, where you can use the previous data, and then you can manipulate the DOM.

Watch will no longer automatically execute the create phase, except to add the immediate execution of the configuration item.

Loading order:

Official documentation highlights two important differences between computed and Method

  • Computed is a property call, and methods is a function call
  • Computed has caching capabilities, whereas Methods does not

Computed properties are cached based on their dependencies and are reevaluated only if its associated dependencies change.

let vm = new Vue({
    el: '#app',
    data: {
        message: 'I am the message,'
    },
    methods: {
        methodTest() {
            return this.message + 'Now I'm using methods'
        }
    },
    computed: {
        computedTest() {
            return this.message + 'Now I use computed.'}}})Copy the code

This means that as long as message has not changed, multiple calls to the computedTest calculated property will immediately return the result of the previous calculation without having to execute the function again.

In contrast, the method call always executes this function whenever a rerender occurs.

<div id="app">
    <h1>{{message}}</h1>
    <p class="test1">{{methodTest}}</p>
    <p class="test2-1">{{methodTest()}}</p>
    <p class="test2-2">{{methodTest()}}</p>
    <p class="test2-3">{{methodTest()}}</p>
    <p class="test3-1">{{computedTest}}</p>
    <p class="test3-2">{{computedTest}}</p>
</div>
Copy the code

In HTML interpolation

  • Computed methods we call in the form of attribute access, {{computedTest}}
  • MethodTest () {{methodTest()}}; otherwise, the view will behave like test1, as shown in the figure below

Computed caching capabilities

In the above example, methods define methods that are accessed as function calls, so test2-1,test2-2, and test2-3 run the methodTest method three times over. If we run into a scenario that requires the return values of 1000 methodtests, So, of course, there’s a lot of waste. And what’s worse, if you change the value of message, then each of those 1000 methodtests will recalculate…

That’s why the official documentation repeatedly states that you should use computed properties for any complex logic

Computed relies on data in data and is reevaluated only when its dependent data changes

let vm = new Vue({
    el: '#app',
    data: {
        message: 'I am the message,'
    },
    methods: {
        methodTest() {
            return this.message + 'Now I'm using methods'
        }
    },
    computed: {
        computedTest() {
            return this.message + 'Now I use computed.'}}})Copy the code

In the example above, a computed definition computedTest method does a calculation and returns a value during Vue instantiation. In subsequent code writing, the computedTest method does not recalculate as long as the message data on which the computedTest method depends does not change. Test3-1 and test3-2 are computedTest recalculations.

This benefit is also obvious. Similarly, if we encounter a scenario that requires the return value of 1000 Computedtests, there is no doubt that compared with methods, the computedTest will only be computed once even if you change the value of message

Other indications of computed

  • Computed is actually accessible as a property and as a method
  • An important reason for computed data is to prevent the logic in text interpolation from being too heavy and difficult to maintain

The computed and watch

Vue provides a more general way to observe and respond to changes in data on Vue instances: the watch property, used in routing scenarios: the router for Vue learning

It’s easy to abuse watch when you have some data that needs to change with other data. A better idea is to use computed attributes rather than mandatory Watch callbacks:

<div id="demo">{{ fullName }}</div>
Copy the code
var vm = new Vue({ 
 el: '#demo',  
data: {   
    firstName: 'Foo',
    lastName: 'Bar', 
    fullName: 'Foo Bar'
  }, 
 watch: {   
 firstName: function (val) { 
     this.fullName = val + ' ' + this.lastName  
  },   
 lastName: function (val) { 
    this.fullName = this.firstName + ' ' + val   
 }
  }
})
Copy the code

The code above is imperative and repetitive. Compare it to the version of the computed attribute:

var vm = new Vue({
    el: '#demo', 
    data: { 
        firstName: 'Foo',
        lastName: 'Bar'
    },
    computed: {
        fullName: function () {
            return this.firstName + ' ' + this.lastName
        }
    }
})
Copy the code

Use Watch when you need to perform asynchronous or expensive operations when data changes.

Bottom line: Try to monitor changes in data with computed properties, because that’s what it is, and with watch there is no computed “automatic”, manual Settings that complicate your code.

At what stage of the life cycle is computed in Vue performed?

1. In new Vue (), _init() in Vue \ SRC \core\instance\index.js initializes each function

function Vue (options) {
if(process.env.NODE_ENV ! = ='production' &&
  !(this instanceof Vue)
) {
  warn('Vue is a constructor and should be called with the `new` keyword'} this._init(options)Copy the code

2. There is an execution order in _init() where initState() is between beforeCreate and created

  initLifecycle(vm)
  initEvents(vm)
  initRender(vm)
  callHook(vm, 'beforeCreate'Be wary when using the initState injection (vm) // be wary when using the initState injection (VM) // be wary when using the initProvide injection (VM) after data/props callHook(vm,'created') 
Copy the code

3. InitState () does these things:

if(opts.props) initProps(VM, opts.props)// Initialization propsif(opts.methods) initMethods(VM, opts.methods)// Initialize methodsif (opts.data) {
  initData(vm)} else {
  observe(vm._data = {}, true/* asRootData */)}// Initializes dataif(opts.computed) initComputed(VM, opts.computed)// Initialize computedCopy the code

4. Therefore, initialization of Props, methods,data, and computed data is performed between beforeCreated and created.