一、基础用法
怎么监听ViewModel的字段值变化?
如下:在watch加上要监听的字段名,function的参数是新值和旧值。
watch: {name: function (val, oval) {this.msg = '你好,我是' + val;},age: function (val, oval) {this.msg = '你好,我是' + this.name + ', 我今年' + val + '岁';}},
例一:
有两个input,分别是name和age,用watch监听字段是否有改变,有就在下面输出一句话 “你好,我是XXX,我今年XX岁”。
完整代码如下:
@{Layout = null;ViewBag.Title = "Home Page";}<!DOCTYPE html><html><head><meta charset="UTF-8"><!-- import CSS --><link rel="stylesheet" href="/element-ui/lib/theme-chalk/index.css"><style>.el-row {margin-bottom: 20px;&:last-child {margin-bottom: 0;}}</style></head><body><div id="app"><el-row :gutter="20"><el-col :span="24"><el-input v-model="name" placeholder="请输入姓名"></el-input></el-col></el-row><el-row :gutter="20"><el-col :span="24"><el-input v-model="age" placeholder="请输入年龄"></el-input></el-col></el-row><el-row :gutter="20"><el-col :span="24"><div>{{msg}}</div></el-col></el-row></div></body><script src="~/scripts/jquery-1.10.2.js"></script><!-- import Vue before Element --><script src="/vue/dist/vue.js"></script><!-- import JavaScript --><script src="/element-ui/lib/index.js"></script><script>new Vue({el: '#app',data: function () {return {name: '',age: 0,msg: ''}},watch: {name: function (val, oval) {this.msg = '你好,我是' + val;},age: function (val, oval) {this.msg = '你好,我是' + this.name + ', 我今年' + val + '岁';}},methods: {}});</script></html>
效果图
二、进阶用法
上面介绍了怎么监听字段值得变化,那么如果我这个字段对应得是一个类呢?
比如这样: 字段user是一个类,有两个字段,然后要实现上面那个例子的功能,要怎么弄?
data: function () {return {user: {name: '',age: 0},msg: ''}},
如下:watch里面的写法是class.field一直迭代下去
watch: {'user.name': function (val, oval) {this.msg = '你好,我是' + val;},'user.age': function (val, oval) {this.msg = '你好,我是' + this.user.name + ', 我今年' + val + '岁';}},
完整代码如下
@{Layout = null;ViewBag.Title = "Home Page";}<!DOCTYPE html><html><head><meta charset="UTF-8"><!-- import CSS --><link rel="stylesheet" href="/element-ui/lib/theme-chalk/index.css"><style>.el-row {margin-bottom: 20px;&:last-child {margin-bottom: 0;}}</style></head><body><div id="app"><el-row :gutter="20"><el-col :span="24"><el-input v-model="user.name" placeholder="请输入姓名"></el-input></el-col></el-row><el-row :gutter="20"><el-col :span="24"><el-input v-model="user.age" placeholder="请输入年龄"></el-input></el-col></el-row><el-row :gutter="20"><el-col :span="24"><div>{{msg}}</div></el-col></el-row></div></body><script src="~/scripts/jquery-1.10.2.js"></script><!-- import Vue before Element --><script src="/vue/dist/vue.js"></script><!-- import JavaScript --><script src="/element-ui/lib/index.js"></script><script>new Vue({el: '#app',data: function () {return {user: {name: '',age: 0},msg: ''}},watch: {'user.name': function (val, oval) {this.msg = '你好,我是' + val;},'user.age': function (val, oval) {this.msg = '你好,我是' + this.user.name + ', 我今年' + val + '岁';}},methods: {}});</script></html>
效果图
如果觉得《Vue.js watch 用法总结》对你有帮助,请点赞、收藏,并留下你的观点哦!