官术网_书友最值得收藏!

Computed properties and watchers

Computed properties are used to avoid complex logic adding bloat to your views. In other words, computed properties are useful to hide the complexity from our HTML and thus keep our HTML understandable, easy to use, and declarative. Put differently, when we need to compute some values from the data option, we can do that with the help of computed properties.

The full code for the following example can be seen at https://codepen.io/AjdinImsirovic/pen/WyXEOz:

<!-- HTML -->
<div id="example">
<p>User name: "{{ message }}"</p>
<p>Message prefixed with a title: "{{ prefixedMessage }}"</p>
</div>

// JS
var example = new Vue({
el: '#example',
data: {
userName: 'John Doe',
title: ''
},
computed: {
// a computed getter
prefixedMessage: function () {
// `this` points to the Vue instance's data option
return this.title + " " + this.userName
}
}
})
Computed properties are cached. As long as a computed property's dependencies do not change, Vue will return the cached value of the computed property.

Watchers are not as frequently used as computed properties are. In other words, the watch option is to be used less frequently than the computed properties option. Watchers are commonly used for asynchronous or otherwise costly operations with changing data.

Watchers have to do with reactive programming; they allow us to observe a sequence of events through time and react to changes as they happen on a certain data property. 

We will cover the subject of computed properties and watchers in later chapters. For now, it is sufficient to know that they exist in Vue and that they are widely used.

主站蜘蛛池模板: 思茅市| 肥东县| 大厂| 彰武县| 兰西县| 中阳县| 萝北县| 宣威市| 武穴市| 曲阜市| 阳曲县| 尼木县| 临武县| 奈曼旗| 澄江县| 陈巴尔虎旗| 泗洪县| 宁化县| 玉树县| 安阳市| 丁青县| 津南区| 贵州省| 革吉县| 准格尔旗| 南丹县| 宾川县| 中西区| 玉树县| 灵台县| 威宁| 河间市| 泗阳县| 剑川县| 方城县| 涡阳县| 河北省| 闻喜县| 大名县| 波密县| 驻马店市|