Home > Web Front-end > JS Tutorial > body text

Vue.js learning computed properties

高洛峰
Release: 2017-02-06 11:19:58
Original
1217 people have browsed it

Preface

Computed properties are used to declaratively describe that a value depends on other values. When you bind data to a computed property in a template, Vue updates the DOM when any of the values ​​it depends on cause the computed property to change. This feature is very powerful and can make your code more declarative, data-driven and easier to maintain.

When you start using Vue, all the data on the template will be put into the data attribute, or sometimes when there are too many variables in the data attribute, you feel that some variables that are only used once are written directly into the template. Later, I saw colleagues in the same group using the computed attribute, so I checked the API again and found that the best thing to use in this situation is computed.

1. Computed can keep the template clear. Try to only display and bind it in the template instead of adding logical operations.

2. Another advantage of using computed is that it will automatically change following changes in other data attributes.

For example, an example from the official document:

var vm = new Vue({
 el: '#demo',
 data: {
 firstName: 'Foo',
 lastName: 'Bar',
 fullName: 'Foo Bar'
 }
})
vm.$watch('firstName', function (val) {
 this.fullName = val + ' ' + this.lastName
})
vm.$watch('lastName', function (val) {
 this.fullName = this.firstName + ' ' + val
})
Copy after login

If you use watch, code redundancy will occur. For example, changes in status during live broadcast can be used to calculate whether to display upper-level attributes such as videos.

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

Summary

The above is all about the computed properties of Vue.js. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

For more articles related to Vue.js learning computed properties, please pay attention to 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