博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Vue.js计算属性
阅读量:2503 次
发布时间:2019-05-11

本文共 2447 字,大约阅读时间需要 8 分钟。



什么是计算属性 (What is a Computed Property)

In Vue.js you can output any data value using parentheses:

在Vue.js中,您可以使用括号输出任何数据值:

This property can host some small computations, for example

该属性可以托管一些小的计算,例如

but you’re limited to a single JavaScript expression.

但您只能使用一个JavaScript 表达式

In addition to this technical limitation, you also need to consider that templates should only be concerned with displaying data to the user, not perform logic computations.

除此技术限制外,您还需要考虑模板应仅与向用户显示数据有关,而不应执行逻辑计算。

To do something more a single expression, and to have more declarative templates, that you use a computed property.

若要使用单个表达式做更多事情,并使用更多声明性模板,请使用计算属性

Computed properties are defined in the computed property of the Vue component:

计算属性是在定义computed的Vue的部件的属性:

计算属性的示例 (An example of a computed property)

Here’s an example code that uses a computed property count to calculate the output. Notice:

这是一个示例代码,它使用计算出的属性count来计算输出。 注意:

  1. I didn’t have to call count(). Vue.js automatically invokes the function

    我不必调用count() 。 Vue.js自动调用该函数

  2. I used a regular function (not an arrow function) to define the count computed property because I need to be able to access the component instance through this.

    我使用常规函数(而非箭头函数)来定义计算count属性,因为我需要能够通过this访问组件实例。

计算属性与方法 (Computed properties vs methods)

If you already know , you may wonder what’s the difference.

如果您已经知道 ,您可能会想知道有什么区别。

First, methods must be called, not just referenced, so you’d need to do call count() instead of count if you have a count method:

首先,方法必须被调用,而不只是引用,所以你需要做的调用count()而不是count ,如果你有一个count方法:

But the main difference is that computed properties are cached.

但是主要的区别是计算的属性被缓存

The result of the count computed property is internally cached until the items data property changes.

count计算属性的结果在内部缓存,直到items数据属性更改。

Important: computed properties are only updated when a reactive source updates. Regular JavaScript methods are not reactive, so a common example is to use Date.now():

重要提示: 仅当React性源更新时才会更新计算的属性。 常规JavaScript方法不是被动的,因此一个常见的示例是使用Date.now()

It will render once, and then it will not be updated even when the component re-renders. Just on a page refresh, when the Vue component is quit and reinitialized.

它只会渲染一次,即使重新渲染组件也不会更新。 当Vue组件退出并重新初始化时,仅刷新页面即可。

In this case a method is better suited for your needs.

在这种情况下,一种方法更适合您的需求。

翻译自:

转载地址:http://woqgb.baihongyu.com/

你可能感兴趣的文章
zt C++ list 类学习笔记
查看>>
git常用命令
查看>>
探讨和比较Java和_NET的序列化_Serialization_框架
查看>>
1、jQuery概述
查看>>
数组比较大小的几种方法及math是方法
查看>>
FTP站点建立 普通电脑版&&服务器版
查看>>
js 给一段代码,给出运行后的最终结果的一些综合情况、
查看>>
webservice 详解
查看>>
js自动补全实例
查看>>
VS无法启动调试:“生成下面的模块时,启用了优化或没有调试信息“
查看>>
npm 安装 sass=-=-=
查看>>
WINFORM中加入WPF控件并绑定数据源实现跨线程自动更新
查看>>
C#类对象的事件定义
查看>>
各类程序员学习路线图
查看>>
HDU 5510 Bazinga KMP
查看>>
关于select @@IDENTITY的初识
查看>>
ASP.NET MVC ajax提交 防止CSRF攻击
查看>>
关于CSS伪类选择器
查看>>
适用于带文字 和图片的垂直居中方法
查看>>
Part 2 - Fundamentals(4-10)
查看>>