官方解释:一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 watch,遍历 watch 对象的每一个 属性。
示例:
<template> <el-card class="box-card"><el-input v-model="name" style="width: 30%;"></el-input></el-card> </template> <script> export default { data() { return { name: '123' }; } }; </script> <style></style>
第一种:常规用法
(1)把要监听的name值看作方法名,来进行监听。【第一种写法】
<template> <el-card class="box-card"><el-input v-model="name" style="width: 30%;"></el-input></el-card> </template> <script> export default { data() { return { name: '123' }; }, watch: { name(newVal, oldVal) { console.log('newVal', newVal);// 1234 console.log('oldVal', oldVal);// 123 } } }; </script> <style></style>
(2)把要监听的name值看作对象,利用hanler方法来进行监听。【第二种写法】
<template> <el-card class="box-card"><el-input v-model="name" style="width: 30%;"></el-input></el-card> </temp