Home  >  Article  >  Web Front-end  >  In-depth understanding of the use of Vue computed properties computed

In-depth understanding of the use of Vue computed properties computed

青灯夜游
青灯夜游forward
2022-08-10 14:39:422295browse

Computed properties are an important part of the Vue component. This article will take you through the Vue computed properties and talk about how to use the computed properties. I hope it will be helpful to you!

In-depth understanding of the use of Vue computed properties computed

#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 expressions can be used in templates, and expressions in templates are very convenient, but this kind of traversal has certain limitations. They are actually used for some Simple calculation. That is, putting too much logic into a template can make it overweight and difficult to maintain. Let's look at an example first:

<div id="app">
    <h1>{{ message.split(&#39;&#39;).reverse().join(&#39;&#39;) }}</h1>
</div>

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 string of the variable message. It becomes more difficult to deal with when you want to reference the flipped string here multiple times in the template. (Learning video sharing: vue video tutorial)

This is why you should use calculated properties for any complex logic. Next, let's learn about computed properties in Vue.

Computed properties can be used to quickly calculate the properties displayed in the view (View). These calculations will be cached and updated only when needed.

There are multiple ways to set values ​​for views in Vue:

  • Use directives to bind data values ​​directly to views

  • Use simple expressions to perform simple conversion of content

  • Use filters to perform simple conversion of content

Except Additionally, we can use computed properties to calculate display values ​​based on a value or a set of values ​​in the data model.

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 an results array in the data model:

data () {
    return {
        results: [
            {
                name: &#39;English&#39;,
                marks: 70
            },
            {
                name: &#39;Math&#39;,
                marks: 80
            },
            {
                name: &#39;History&#39;,
                marks: 90
            }
        ]
    }
}

Suppose we want to see the total number for all topics. We cannot use filters or expressions to accomplish this task.

filters: Used for simple data formats, which are required in multiple places in the application

expressions: Stream operations or other complex logic are not allowed. They should be kept simple

This is where computed properties come in handy. We can add a calculated value to the model as follows:

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
    }
}

totalMarksThe calculated property calculates the total value using the marks of the array resultes. It just loops through the values ​​and returns the subtotal.

Then we can display the calculated value in the view:

<div id="app">
    <div v-for="subject in results">
        <input v-model="subject.marks">
        <span>Marks for {{ subject.name }}: {{ subject.marks }}</span>
    </div>
    <div>
        Total marks are: {{ totalMarks }}
    </div>
</div>

The effect is as follows:

Calculated attributes vs methods

We can use the method in Vue to calculate the total score of the subject, and the final total result is the same.

Based on the above example, we moved the totalMarks function in the computed block to methods. At the same time, replace {{ totalMarks }} with {{ totalMarks() }} in the template. You end up seeing the same result, as shown below:

#Although the output of both methods is the same, the performance will suffer. of blow. With this approach, the totalMarks() method is executed once every time the page is rendered (i.e., with every change).

If we have a computed property, then Vue will remember the value that the calculated 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 results has not changed, multiple accesses to the totalMarks calculated property will immediately return the previous calculated results without having to execute the function again.

The above two examples also show that calculated properties in Vue 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 calculated properties will no longer be updated, because

Date.now() is not a reactive dependency:

computed: {
    now: function () {
        return Date.now()
    }
}

In contrast Next, the method is called in such a way that the function will always be executed again whenever a re-render is triggered. Therefore, the function must be a pure function. It must not have side effects. The output can only depend on the value passed to the function.

那么我们为什么需要缓存?假设我们有一个性能开销比较大的的计算属性 A,它需要遍历一个极大的数组和做大量的计算。然后我们可能有其他的计算属性依赖于 A 。如果没有缓存,我们将不可避免的多次执行 Agetter!如果你不希望有缓存,请用方法来替代。

计算属性的 setter

计算属性默认只有getter,不过在需要时你也可以提供一个setter:

computed: {
    fullName: {
        // getter
        get: function () {
            return this.firstName + &#39; &#39; + this.lastName
        },
        // setter
        set: function (newValue) {
            var names = newValue.split(&#39; &#39;)
            this.firstName = names[0]
            this.lastName = names[names.length - 1]
        }
    }
}

效果如下:

你在输入框中输入一个fullName,然后点击set按钮,可以看到对应的效果。你现在再运行app.fullName="Airen liao"时,计算属性的setter会被调用,app.firstNameapp.lastName也相应地会被更新。如下图所示:

In-depth understanding of the use of Vue computed properties computed

观察者

虽然计算属性在大多数情况下更合适,但有时候也需要一个自定义的watcher。这是为什么Vue通过watch选项提供一个更通用的方法,来响应数据的变化。当你想要在数据变化响应时,执行异步操作或开销较大的操作,这是很有用的。

Vue确实提供了一种更通用的方式来观察和响应Vue实例上的数据变动:watch属性。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用watch。然而,通常更好的想法是使用计算属性而不是命令式的watch回调。比如下面的示例:

<div id="app">
    {{ fullName }}
</div>

let app = new Vue({
    el: &#39;#app&#39;,
    data () {
        return {
            firstName: &#39;Foo&#39;,
            lastName: &#39;Bar&#39;,
            fullName: &#39;Foo Bar&#39;
        }
    },
    watch: {
        firstName: function (val) {
            this.fullName = val + &#39; &#39; + this.lastName
        },
        lastName: function (val) {
            this.fullName = this.firstName + &#39; &#39; + val
        }
    }
})

上面代码是命令式的和重复的。将它与计算属性的版本进行比较:

let app = new Vue({
    el: &#39;#app&#39;,
    data () {
        return {
            firstName: &#39;Foo&#39;,
            lastName: &#39;Bar&#39;
        }
    },
    computed: {
        fullName: function () {
            return this.firstName + &#39; &#39; + this.lastName
        }
    }
})

在Vue中使用异步计算属性

Vue中的计算属性非常好。它们允许你执行复杂的操作或数据格式,同时最大限度地执行依赖项计算的性能,只在依赖更改时更新视图。但遗憾的是,它们完全是同步的。

值得庆幸的是,有一个插件。使用vue-async-computed包可以通地将一个promise的值绑定到组件属性来创建和使用组件中的异步计算属性。

我们可以在项目的根目录下通过yarnnpm来安装vue-async-computed插件:

# Yarn
$ yarn add vue-async-computed
# NPM
$ npm i vue-async-computed --save

接下来在你的项目中开启这个插件:

// main.js
import Vue from &#39;vue&#39;;
import AsyncComputed from &#39;vue-async-computed&#39;
import App from &#39;App.vue&#39;;

Vue.use(AsyncComputed);

new Vue({
    el: &#39;#app&#39;,
    render: h => h(App)
});

如果你和我一样,对Vue的构建工具不是很熟悉的话,我建议你使用Vue官方提供的构建工具 Vue CLI。默认情况,它提供了五种模板,你可以根据自己喜欢的方式选择自己需要的模板即可。

确认在项目中引用vue-async-computed之后,咱们就可以开始使用这个插件了。使用如何使用这个插件之前,先来简单的了解一些概念。

在Vue中标准计算属性和异步属性之间有一些区别:

  • 异步属性不能有setter

  • 直到promiseresolve为止,除非default被设置,否则该值为null

在大多数情况下,你可以将它们视为返回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(&#39;*Fancy* Resolved Value!&#39;), 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(&#39;*Fancy* Resolved Value!&#39;), 1000)
        })
    }
    export default {
        asyncComputed: {
            async myResolvedValue() {
                return await fancinessComesLater()
            }
        }
    }
</script>

有关于vue-async-computed更详细的使用和介绍,可以阅读其官网提供的相关介绍。

总结

今天主要学习了Vue中的计算属性。在Vue中的计算属性可以让我们很好的监听多个数据或者一个数据来维护返回一个状态值,只要其中一个或多个数据发生变化,则会重新计算整个函数体,重新皇家马德里回状态值,从而更新对应的视图(View)。其次,计算属性具有缓存,相比Vue中的方法而言,性能更佳。但Vue中的计算属性都是同步的,如果需要异步我们得依赖于vue-async-computed。

原文地址:https://www.w3cplus.com/vue/vue-computed-intro.html

(Learning video sharing: web front-end development, Basic programming video)

The above is the detailed content of In-depth understanding of the use of Vue computed properties computed. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:w3cplus.com. If there is any infringement, please contact admin@php.cn delete