1、computed:计算属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。
2、methods:methods 将被混入到 Vue 实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例。
3、watch:是一种更通用的方式来观察和响应 Vue 实例上的数据变动。一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个属性。
通俗来讲,
computed是在HTML DOM加载后马上执行的,如赋值;
而methods则必须要有一定的触发条件才能执行,如点击事件;
watch呢?它用于观察Vue实例上的数据变动。对应一个对象,键是观察表达式,值是对应回调。值也可以是方法名,或者是对象,包含选项。
computed用法
<template>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</template>
export default {
name: 'Home',
data: function () {
return {
......
}
},
computed: {
// 计算属性的 getter
reversedMessage: function () {
// console.log('1')
return this.msg.split('').reverse().join('')
}
}
methods用法
<template>
<p>{{msg}}</p>
<button v-on:click="reverseMessage">逆转消息</button>
</template>
export default {
name: 'Home',
data: function () {
return {
......
msg: 'this msg for vue.js!!!',
......
}
},
methods: {
reverseMessage: function () {
this.msg = this.msg.split('').reverse().join('')
return this.msg
}
watch用法
<template>
{{firstname}}
<button @click="firstname = 'change complete'">修改txt</button>
</template>
export default {
name: 'Home',
data: function () {
return {
......
firstname: 'hello',
......
}
},
watch: {
firstname: function (newval, oldval) {
console.log(oldval, newval)
}