Home > Web Front-end > Vue.js > How to use computed attributes to process responsive data in Vue

How to use computed attributes to process responsive data in Vue

PHPz
Release: 2023-06-11 12:32:42
Original
4965 people have browsed it

Vue is a progressive JavaScript framework for building user interfaces. In Vue, responsive updating of data is one of Vue's most powerful features. In Vue, data binding is one-way, that is, changes in data will affect the interface, but operations on the interface (such as user input, etc.) will not affect the data. These data updates are automatically completed through the computed property in Vue.

The computed property is a method used in Vue to process responsive data. Its essence is a calculated property. Compared with the methods in Vue, the computed attribute focuses more on processing data calculation and data caching, allowing Vue to update data more efficiently. This article will introduce how to use the computed attribute and related precautions.

Basic usage of computed attributes

The method of declaring computed attributes in Vue is very simple. Just add a computed object to the Vue instance, for example:

var vm = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  computed: {
    reversedMessage: function () {
      return this.message.split('').reverse().join('')
    }
  }
})
Copy after login

In In the above code, we declare a Vue instance and define a reversedMessage property in the computed object, which uses the message property for calculation. When the value of the message attribute changes, Vue will automatically update the calculated value of reversedMessage and render it to the interface.

It should be noted that the computed attribute must be a function. This function can receive parameters or not. Inside the function, use this to access the data in the Vue instance, but not directly access the variables.

In addition, the value of the computed attribute will be cached and will only be recalculated when the dependent data changes, which can greatly improve the efficiency of Vue. For example, in the above example, when the value of the message attribute remains unchanged, each time the reversedMessage attribute is read, the calculated value in the cache will be directly returned and will not be recalculated.

Advanced usage of the computed attribute

The setter in the computed attribute

The computed attribute can not only be used to read data, but also can be used to set data. The set method defined in the computed attribute will be called when the attribute is assigned a value. For example:

var vm = new Vue({
  el: '#app',
  data: {
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    fullName: {
      get: function () {
        return this.firstName + ' ' + this.lastName
      },
      set: function (newVal) {
        var names = newVal.split(' ')
        this.firstName = names[0]
        this.lastName = names[names.length - 1]
      }
    }
  }
})
Copy after login

In the above example, we defined a fullName attribute, which is readable and writable. We defined a get method that returns the combined string of firstName and lastName. At the same time, a set method is also defined, which receives a parameter newVal and sets the values ​​of firstName and lastName according to this parameter. It should be noted that the setter function in the computed attribute does not return any value.

Dependence of computed attributes

The calculation of computed attributes is based on the attributes on which it depends. When the dependent properties change, the computed properties are automatically recalculated. Vue can automatically collect dependencies used in computed attributes through the dependency tracking mechanism. For example:

var vm = new Vue({
  el: '#app',
  data: {
    firstName: 'John',
    lastName: 'Doe'
  },
  computed: {
    fullName: function () {
      console.log('computed fullName')
      return this.firstName + ' ' + this.lastName
    },
    reversedName: function () {
      console.log('computed reversedName')
      return this.fullName.split('').reverse().join('')
    }
  }
})

console.log(vm.reversedName)
vm.firstName = 'Tom'
console.log(vm.reversedName)
Copy after login

In the above code, both fullName and reversedName depend on the two properties firstName and lastName. When we access the reversedName property, Vue will automatically calculate the values ​​of fullName and reversedName, and output computed fullName and computed reversedName. When the value of firstName is modified, Vue will recalculate the values ​​of fullName and reversedName, and output computed fullName and computed reversedName.

It should be noted that when the data that the computed attribute depends on changes, the getter in the computed attribute is called asynchronously. This means that when the dependent data changes, Vue will not update the value of the computed property immediately, but will update it in the next event loop. This avoids unnecessary performance overhead.

The difference between computed properties and watch properties

In addition to computed properties, Vue also provides another way to process responsive data - watch properties. They all have the ability to handle reactive data, but they differ in how they implement it.

The watch attribute is a listener. When a data changes, the watch attribute will immediately execute a response function and have the side effect of processing the data. For example:

var vm = new Vue({
  el: '#app',
  data: {
    firstName: 'John',
    lastName: 'Doe',
    fullName: ''
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})
Copy after login

In the above example, we defined the watch attribute to listen for changes in data and update the value of the fullName attribute when firstName or lastName changes. It should be noted that the processing function in the watch attribute will be executed immediately when the data changes.

The biggest difference between the computed attribute and the watch attribute lies in their implementation and usage scenarios. The computed attribute is more suitable for handling repetitive operations such as data calculation and caching, which can greatly improve the efficiency of Vue. The watch attribute is more suitable for monitoring data changes, such as triggering animation effects or sending requests and other side-effect operations when the data changes.

Conclusion

In Vue, the computed attribute is one of the most commonly used methods to handle reactive data. The computed attribute allows us to process data more concisely and efficiently, avoiding repeated calculations, and also improves the performance of Vue. When using the computed attribute, you need to pay attention to the setter function, dependency relationship, and the difference between the computed attribute and the watch attribute in the computed attribute.

The above is the detailed content of How to use computed attributes to process responsive data in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template