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

  • Vue.js Quick Start Guide
  • Ajdin Imsirovic
  • 263字
  • 2021-06-24 18:23:56

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.

主站蜘蛛池模板: 唐山市| 达日县| 朝阳区| 崇州市| 四会市| 辽源市| 泸溪县| 奈曼旗| 秦安县| 奎屯市| 咸宁市| 新竹市| 嘉义县| 孟连| 乌兰察布市| 连江县| 巨野县| 即墨市| 广东省| 铜梁县| 博白县| 龙海市| 花莲县| 镇巴县| 社旗县| 兴化市| 宁武县| 精河县| 绿春县| 望城县| 天祝| 梓潼县| 咸宁市| 东丰县| 通辽市| 三亚市| 阳泉市| 阿荣旗| 乐至县| 扶风县| 隆化县|