1. 程式人生 > >vue computed和 methods、 watch 區別(鄒文豐)

vue computed和 methods、 watch 區別(鄒文豐)

pre script 重新 lln reverse body utf 依賴 ()

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<body>
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
<div>{{test1}}</div>
<button @click="add_1">點擊</button>
<!--<div id="demo">{{ fullNames }}</div>-->
</div>
<script>
var vm = new Vue({
el: ‘#example‘,
data: {
message: ‘您好!‘,
test1:1,
firstName: ‘Foo‘,
lastName: ‘Bar‘,
fullName: ‘Foo Bar‘
},
computed: {
reversedMessage: function (test) {
console.log(test);
return this.message.split(‘‘).reverse().join(‘‘)
},
},
methods:{
add_1:function () {
this.message=‘你好呀!‘;
alert(this.reversedMessage);
return this.test1++
}
},
watch:{
// firstName: function (val) {
// this.fullName = val + ‘ ‘ + this.lastName
// },
// lastName: function (val) {
// this.fullName = this.firstName + ‘ ‘ + val
// }
}
})
//1.computed 計算屬性 緩存 計算屬性是基於它們的依賴進行緩存的。計算屬性只有在它的相關依賴發生改變時才會重新求值;優點減少代碼遍歷,直接得到緩存數據。
//2.methods 事件方法普通事件
//3.watch 偵聽器 雖然計算屬性在大多數情況下更合適,但有時也需要一個自定義的偵聽器。這就是為什麽 Vue 通過 watch 選項提供了一個更通用的方法,來響應數據的變化。
// 當需要在數據變化時執行異步或開銷較大的操作時,這個方式是最有用的。
</script>
</body>
</html>

vue computed和 methods、 watch 區別(鄒文豐)