1基本使用
函数中两个参数:newVal表示更新过的值,oldVal表示原来没有更新过的值 使用watch属性可以监视data中指定数据的变化,然后触发watch中对应的function处理函数
<div id="app"><input type="text" v-model="num1">+<input type="text" v-model="num2">=<input type="text" v-model="num3"></div><script src="../js/vue.js"></script><script>const vm=new Vue({el:"#app",data:{num1:"",num2:"",num3:""},watch: {//newVal表示更新过的值,oldVal表示原来没有更新过的值//使用watch属性可以监视data中指定数据的变化,然后触发watch中对应的function处理函数//这里的'num1','num2'是指this.num1,this.num2'num1':function(newVal,oldVal){this.num3=newVal+this.num2},'num2':function(newVal,oldVal){this.num1this.num3=this.num1+newVal}},})
2.监听路由
<div id="app"><router-link to="/login" tag="button">登录</router-link><router-link to="/register" tag="button">注册</router-link><!-- 容器 --><router-view></router-view></div><!-- 登录组件 --><template id="login"><div>这是登录组件</div></template><!-- 注册组件 --><template id="register"><div>这是注册组件</div></template><script src="../js/vue.js"></script><script src="../js/vue-router.js"></script><script>const Login={template:"#login"}const Register={template:"#register"}const router=new VueRouter({routes:[{path:"",redirect: "/login"},{path:"/login",component:Login},{path:"/register",component:Register}],linkActiveClass: 'myactive' ,// mode:"history"})const vm=new Vue({el:"#app",data:{},methods:{},router,components: {Login,Register},watch:{//这里$route.path指的就是this.router.path"$route.path":function(newVal,oldVal){if(newVal==="/login"){console.log("欢迎进入登录页面");}else if(newVal==="/register"){console.log("欢迎进入注册页面");}}}})</script>
3.监听多个事件
<template><div><button @click="changename">调用</button></div></template><script>export default {data(){return {name: 'Joe'}},watch: {name: ['sayName1',function(newVal, oldVal) {this.sayName2()},{handler: 'sayName3',immaediate: true}]},methods: {sayName1() {console.log('sayName1==>', this.name)},sayName2() {console.log('sayName2==>', this.name)},sayName3() {console.log('sayName3==>', this.name)},//这里修改name属性,通过修改name属性来触发watch中的事件changename(){this.name="wangsu"}}}</script>
