Home > Article > Web Front-end > How to use the computed attribute in Vue
This time I will show you how to use the computed attribute in Vue. What are the precautions for using the computed attribute in Vue? The following is a practical case, let's take a look.
The computed properties in Vue are called computed properties . In this section, we learn how to use calculated properties in Vue? Remember when you were learning about Vue's template-related knowledge, you knew that you can use<p id="app"> <h1>{{ message.split('').reverse().join('') }}</h1> </p>In this example, the template is no longer simple and clear. You have to watch for a while to realize that here you want to display the flipped This is why for any complex logic you should use computed properties. Next, let's learn about computed properties in Vue. Computed properties can be used to quickly calculate properties displayed in a view. These calculations will be cached and updated only when needed. There are multiple ways to set values for views in Vue:
Computed properties
Computed properties allow us to perform complex value calculations on a specified view. These values will be bound to the dependency values and only updated when needed. For example, we could have a results array in the data model:data () { return { results: [ { name: 'English', marks: 70 }, { name: 'Math', marks: 80 }, { name: 'History', marks: 90 } ] } }Suppose we want to see the total number of all topics. We cannot use filters or expressions to accomplish this task.
computed: { totalMarks: function () { let total = 0 let me = this for (let i = 0; i < me.results.length; i++) { total += parseInt(me.results[i].marks) } return total } }The totalMarks calculated attribute uses the marks in the array resultses to calculate the total value. It just loops through the values and returns the subtotal. We can then display the calculated value in the view:
<p id="app"> <p v-for="subject in results"> <input v-model="subject.marks"> <span>Marks for {{ subject.name }}: {{ subject.marks }}</span> </p> <p> Total marks are: {{ totalMarks }} </p> </p>
Computed properties vs methods
We can use the method in Vue to calculate the total score of the subject, and the final total result will be the same. Based on the above example, we move the totalMarks function in the computed block to methods. Also replace {{ totalMarks }} with {{ totalMarks() }} in the template. You end up seeing the same result, as shown below:let app = new Vue({ el: '#app', data () { return { results: [ { name: '英语', marks: 70 }, { name: '数学', marks: 80 }, { name: '历史', marks: 90 } ] } }, methods: { totalMarks: function () { let total = 0 let me = this for (let i = 0; i < me.results.length; i++) { total += parseInt(me.results[i].marks) } return total } } })Although the output results of these two methods are the same, the performance will suffer a devastating blow. With this approach, the totalMarks() method is executed once every time the page is rendered (for example, with every change ). If we have a computed property, then Vue will remember the value that the computed property depends on (in our case, that is results ). By doing this, Vue can only calculate values when dependencies change. Otherwise, the previously cached value will be returned. This also means that as long as the results have not changed, multiple visits The totalMarks computed property immediately returns the result of the previous calculation without having to execute the function again. The above two examples also illustrate that in Vue, calculated properties are cached based on their dependencies, but methods are not cached based on their dependencies. Thus using computed properties has better performance than methods. This also means that the following computed property will no longer be updated because Date.now() is not a reactive dependency:
computed: { now: function () { return Date.now() } }
相比之下,每当触发重新渲染时,方法的调用方式将总是再次执行函数。因此,函数必须是一个纯函数。它不能有副作用。输出只能依赖于传递给函数的值。
那么我们为什么需要缓存?假设我们有一个性能开销比较大的的计算属性 A ,它需要遍历一个极大的数组和做大量的计算。然后我们可能有其他的计算属性依赖于 A 。如果没有缓存,我们将不可避免的多次执行 A 的 getter !如果你不希望有缓存,请用方法来替代。
计算属性的 setter
计算属性默认只有 getter ,不过在需要时你也可以提供一个 setter :
computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } }
你在输入框中输入一个 fullName ,然后点击 set 按钮,可以看到对应的效果。你现在再运行 app.fullName="Airen liao" 时,计算属性的 setter 会被调用, app.firstName 和 app.lastName 也相应地会被更新。
观察者
虽然计算属性在大多数情况下更合适,但有时候也需要一个自定义的 watcher 。这是为什么Vue通过 watch 选项提供一个更通用的方法,来响应数据的变化。当你想要在数据变化响应时,执行异步操作或开销较大的操作,这是很有用的。
Vue确实提供了一种更通用的方式来观察和响应Vue实例上的数据变动: watch 属性 。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用 watch 。然而,通常更好的想法是使用计算属性而不是命令式的 watch 回调。比如下面的示例:
<p id="app"> {{ fullName }} </p> let app = new Vue({ el: '#app', data () { return { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' } }, watch: { firstName: function (val) { this.fullName = val + ' ' + this.lastName }, lastName: function (val) { this.fullName = this.firstName + ' ' + val } } })
上面代码是命令式的和重复的。将它与计算属性的版本进行比较:
let app = new Vue({ el: '#app', data () { return { firstName: 'Foo', lastName: 'Bar' } }, computed: { fullName: function () { return this.firstName + ' ' + this.lastName } } })
在Vue中使用异步计算属性
Vue中的计算属性非常好。它们允许你执行复杂的操作或数据格式,同时最大限度地执行依赖项计算的性能,只在依赖更改时更新视图。但遗憾的是,它们完全是同步的。
值得庆幸的是,有一个插件。使用vue-async-computed 包可以通地将一个 promise 的值绑定到组件属性来创建和使用组件中的异步计算属性。
我们可以在项目的根目录下通过 yarn 或 npm 来安装 vue-async-computed 插件:
# Yarn $ yarn add vue-async-computed # NPM $ npm i vue-async-computed --save
接下来在你的项目中开启这个插件:
// main.js import Vue from 'vue'; import AsyncComputed from 'vue-async-computed' import App from 'App.vue'; Vue.use(AsyncComputed); new Vue({ el: '#app', render: h => h(App) });
如果你和我一样,对Vue的构建工具不是很熟悉的话,我建议你使用Vue官方提供的构建工具 Vue CLI 。默认情况,它提供了五种模板,你可以根据自己喜欢的方式选择自己需要的模板即可。
确认在项目中引用 vue-async-computed
之后,咱们就可以开始使用这个插件了。使用如何使用这个插件之前,先来简单的了解一些概念。
在Vue中标准计算属性和异步属性之间有一些区别:
异步属性不能有 setter
在大多数情况下,你可以将它们视为返回 promise
的计算属性。
<!-- MyComponent.vue --> <template> <!-- 在一两秒后 myResolvedValue将变成"*Fancy* Resolved Value" --> <h2>Asynchronous Property {{ myResolvedValue }}</h2> </template> <script> export default { asyncComputed: { myResolvedValue () { return new Promise((resolve, reject) => { setTimeout(() => resolve('*Fancy* Resolved Value!'), 1000) }) } } } </script>
使用ES7 / ES2016的 async / await ,这将变得更简单:
<!-- MyComponent.vue --> <template> <!-- 在一两秒后 myResolvedValue将变成"*Fancy* Resolved Value" --> <h2>Asynchronous Property {{ myResolvedValue }}</h2> </template> <script> function fancinessComesLater () { return new Promise((resolve, reject) => { setTimeout(() => resolve('*Fancy* Resolved Value!'), 1000) }) } export default { asyncComputed: { async myResolvedValue() { return await fancinessComesLater() } } } </script>
有关于vue-async-computed 更详细的使用和介绍,可以阅读其 官网 提供的相关介绍。
总结
今天主要学习了Vue中的计算属性。在Vue中的计算属性可以让我们很好的监听多个数据或者一个数据来维护返回一个状态值,只要其中一个或多个数据发生变化,则会重新计算整个函数体,重新皇家马德里回状态值,从而更新对应的视图(View)。其次,计算属性具有缓存,相比Vue中的方法而言,性能更佳。但Vue中的计算属性都是同步的,如果需要异步我们得依赖于vue-async-computed 。
Since I am a beginner in Vue, my understanding of Vue's computational properties is only superficial. If you look at it from a deeper level, there will still be certain problems. I hope you guys can correct me or provide your own experience.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the use of native ajax get and post methods
Node.js injects large amounts of data into MySQL
Use requireJS to add the return to top function
The above is the detailed content of How to use the computed attribute in Vue. For more information, please follow other related articles on the PHP Chinese website!