Summary of the differences between Vue's watch, computed, and methods

Summary of the differences between Vue's watch, computed, and methods

1 Introduction

When creating a Vue instance, you can pass in an options object

const vm = new Vue({
  data: {
    msg: 'hello'
  },
  computed: {},
  methods: {},
  watch: {}
})

This options object can specify a lot of options (or attributes), and data-related options include but are not limited to data , methods , computed, watch , etc.

Among them, methods , computed , and watch can all process or respond to data through functions. There are differences between these three, but it is easy to confuse them.

2 Basic usage

Use script to introduce vue.js The following codes are all run in the following html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Methods</title>
    <!-- Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  </head>
  <body>
    
  </body>
  <script>
    
  </script>
</html>

2.1 Methods

The functions defined in the methods option are called methods. During the Vue instantiation process, the methods in methods object will be mixed into the Vue instance and become methods of the Vue instance. These methods can be accessed directly through the Vue instance

<body>
  <div id="example">
    <!-- Display: a:1 -->
    <p>a:{{ plus() }}</p> 
  </div>
</body>
<script>
  const vm = new Vue({
    el: "#example",
    data: {
      a: 0,
    },
    methods: {
      plus: function () {
        return this.a + 1;
      },
    },
  });
  console.log(vm); // View the console output of vm, you can see that it has a method: plus: ƒ (), ⚠️Note that it is a method console.log(vm.plus()); // Access the method directly through the vm instance, output: 1
</script>


The function in methods needs to be called actively to execute. The value of a does not update <p>a:{{plus()}}</a> in the page.

2.2 computed properties

The function defined in the computed option is called a computed property. During the Vue instantiation process, the computed properties in computed object will be mixed into the Vue instance and become properties of the same name of the Vue instance.

<body>
  <div id="example">
    <!-- Display: a:1 -->
    <p>a:{{ plus }}</p>
  </div>
</body>
<script>
  const vm = new Vue({
    el: "#example",
    data: {
      a: 0,
    },
    computed: {
      plus: function () {
        return this.a + 1;
      },
    },
  });
  console.log(vm); // // Check the vm output by the console, you can see that it has an attribute: plus:1, ⚠️Note that it is an attribute</script>

At first glance it seems that computed and methods have the same functionality, and indeed in this example they have the same effect.

In fact, the difference between the two has been reflected by printing the vm instance and the access method:

  • The functions in methods will become methods of vm
  • After calculation, the function in computed will become the attribute of the same name of vm , and the attribute value is the calculation result of the function, that is, the return value

In addition, unlike methods, computed properties can be updated responsively as the data they depend on changes, that is, when a changes, plus property will also be updated.

2.3 watch listener

The key-value pair in the watch option is called a listener or a listening property/listening property. The key is the expression to be observed, and the value is the corresponding callback function (the value can also be in other forms, which are not expanded here)

During the Vue instantiation process, the variables that need to be monitored will be recorded, and when these variables change, the corresponding callback function will be executed

<body>
  <div id="example">
    <!-- Display: a:1 -->
    <p>a:{{ a }}</p>
  </div>
</body>
<script>
  const vm = new Vue({
    el: "#example",
    data: {
      a: 0,
    },
    watch:
      a: function () {
        console.log("a has changed"); // Because the value of a has changed, the callback function executes console.log(this.a);
      },
    },
  });
  vm.a = 1; // Manually change the value of a here</script>

3 Differences between the three

3.1 Methods vs. Computed Properties

In addition to the two differences mentioned in 2.2, the most important difference is:

  • Computed properties are cached based on their responsive dependencies, that is, the evaluation function will be re-triggered only when a in the above text changes, otherwise multiple calls will be evaluated from the cache, which is very useful for expensive calculations to avoid repeated calculations.
  • Methods are always re-executed when called

The following table summarizes the differences between the two:

methods computed
What becomes the vm instance after Vue is instantiated Become a method on the vm instance Becomes a property on the vm instance
Can it be updated responsively based on dependent data? No, you need to actively call the method able
Can it be cached? No, each call is re-executed Yes, the dependent data remains unchanged and the value will be taken from the cache

3.2 Computed Properties vs Listeners

  • The first and most obvious difference is that the naming method of the listener is fixed. You have to give the same name to the person you want to listen to. Methods and computed properties can be named arbitrarily
  • Secondly, the listener cannot actively access, while the other two can actively access
  • Use cases for computed properties and listeners:

If a value needs to be calculated from one or more data, use a calculated property

The listening property is mainly used to monitor changes in a certain value and then perform the required logical processing; in addition, when it is necessary to perform asynchronous or costly operations when data changes, the listening property is more useful. For specific examples, see the vue document - listener

This is the end of this article about the differences between Vue's watch , computed , and methods . For more information about the differences between Vue 's watch , computed , and methods , please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The difference between methods, watch, and computed in Vue

<<:  Use of kubernetes YAML files

>>:  Cross-browser development experience summary (I) HTML tags

Recommend

How to enable TLS and CA authentication in Docker

Table of contents 1. Generate a certificate 2. En...

How to make your JavaScript functions more elegant

Table of contents Object parameters using destruc...

MySQL 8.0.15 winx64 installation and configuration method graphic tutorial

This article shares the installation and configur...

Several ways to clear arrays in Vue (summary)

Table of contents 1. Introduction 2. Several ways...

MySQL 8.0.11 installation summary tutorial diagram

Installation environment: CAT /etc/os-release Vie...

Detailed description of shallow copy and deep copy in js

Table of contents 1. js memory 2. Assignment 3. S...

Detailed explanation of the usage and differences of MySQL views and indexes

MySQL Views Simply put, a MySQL view is a shortcu...

The difference between html block-level tags and inline tags

1. Block-level element: refers to the ability to e...

How to implement dual-machine master and backup with Nginx+Keepalived

Preface First, let me introduce Keepalived, which...

React handwriting tab switching problem

Parent File import React, { useState } from '...

A brief analysis of crontab task scheduling in Linux

1. Create a scheduling task instruction crontab -...

Implementation and optimization of MySql subquery IN

Table of contents Why is IN slow? Which is faster...

SQL-based query statements

Table of contents 1. Basic SELECT statement 1. Qu...

Vue+Openlayer uses modify to modify the complete code of the element

Vue+Openlayer uses modify to modify elements. The...

Detailed explanation of script debugging mechanism in bash

Run the script in debug mode You can run the enti...