案例

把firstName和lastName组合成fullName

为keyup事件绑定方法

<body>

<div id="app">
<!-- 为keyup事件绑定函数 -->
<input type="text" v-model="firstName" @keyup="getFullName" /> +
<input type="text" v-model="lastName" @keyup="getFullName" /> =
<input type="text" v-model="fullName" />
</div>

<!-- 导入js -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>

var vue = new Vue({
el: "#app",
data: {
firstName: "",
lastName: "",
fullName: ""
},
methods: {
getFullName: function () {
this.fullName = this.firstName + this.lastName
}
}
})
</script>
</body>

watch

<body>

<div id="app">
<input type="text" v-model="firstName" /> +
<input type="text" v-model="lastName" /> =
<input type="text" v-model="fullName" />
</div>

<!-- 导入js -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
var vue = new Vue({
el: "#app",
data: {
firstName: "",
lastName: "",
fullName: ""
},
// 使用这个属性,可以监听data中指定数据的变化,然后触发watch中对应的function函数
watch: {
// 第一个参数最新的值,第二个参数旧的值
firstName: function (newVal, oldVal) {
this.fullName = newVal + this.lastName
},
lastName: function (newVal, oldVal) {
this.fullName = this.firstName + newVal
}
}
})
</script>
</body>

computed

<body>

<div id="app">
<input type="text" v-model="firstName" /> +
<input type="text" v-model="lastName" /> =
<input type="text" v-model="fullName" />
</div>

<!-- 导入js -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
var vue = new Vue({
el: "#app",
data: {
firstName: "",
lastName: "",
},
computed: {
fullName: function () {
return this.firstName + this.lastName
}
}
})
</script>
</body>

总结

  • watch擅长处理的场景:一个数据影响多个数据
  • computed擅长处理的场景:一个数据受多个数据影响
  • methods里面定义的函数,是需要主动调用的,而和watch和computed相关的函数,会自动调用,完成我们希望完成的作用