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

How to use the computed attribute in Vue

php中世界最好的语言
Release: 2018-04-17 14:23:13
Original
14167 people have browsed it

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

expression in the template, and the expressions in the template are very convenient, but this kind of traversal has certain limitations. They It is actually used for some simple operations. That is, putting too much logic into a template can make it overweight and difficult to maintain. Let’s take a look at an example first:

<p id="app">
  <h1>{{ message.split('').reverse().join('') }}</h1>
</p>
Copy after login
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.

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:

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

  • Use simple expressions to perform simple transformations on content
  • Use
  • FiltersSimple conversion of content

Apart from this, we can also use computed properties to calculate the display value 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 a results array in the data model:

data () {
  return {
    results: [
      {
        name: 'English',
        marks: 70
      },
      {
        name: 'Math',
        marks: 80
      },
      {
        name: 'History',
        marks: 90
      }
    ]
  }
}
Copy after login
Suppose we want to see the total number of 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 : Does not allow the use of stream operations or other complex logic. They should keep it simple
# At this time, computed properties can 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
  }
}
Copy after login
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>
Copy after login

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
  }
 }
})
Copy after login
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()
  }
}
Copy after login

相比之下,每当触发重新渲染时,方法的调用方式将总是再次执行函数。因此,函数必须是一个纯函数。它不能有副作用。输出只能依赖于传递给函数的值。

那么我们为什么需要缓存?假设我们有一个性能开销比较大的的计算属性 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]
    }
  }
}
Copy after login

你在输入框中输入一个 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
    }
  }
})
Copy after login

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

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

在Vue中使用异步计算属性

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

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

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

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

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

// 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)
});
Copy after login

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

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

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

  • 异步属性不能有 setter

  • 直到 promise 的 resolve 为止,除非 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('*Fancy* Resolved Value!'), 1000)
        })
      }
    }
  }
</script>
Copy after login

使用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>
Copy after login

有关于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!

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