- 通过watch监听Model中数据的变化, 只要数据发生变化, 就会自动调用对应的回调函数
body>
<div id="app">
<input type="text" v-model="num1">
<span>+</span>
<input type="text" v-model="num2">
<span>=</span>
<input type="text" v-model="res" disabled>
</div>
<script>
let vue = new Vue({
el:'#app',
data:{
num1:0,
num2:0,
res:0
},
watch:{
num1(){//当num1数据变化时触发该回调函数
this.res= parseInt(this.num1) +parseInt(this.num2)
},
num2(){//当num2数据变化时触发该回调函数
this.res= parseInt(this.num1) +parseInt(this.num2)
}
}
})
</script>
</body>
2. 通过wach监听路由地址的变化
<body>
<div id="app">
<a href="#/one">切换到第一个界面</a>
<a href="#/two">切换到第二个界面</a>
<router-view></router-view>
</div>
<template id="one">
<div class="onepage">
<p>我是第一个界面</p>
</div>
</template>
<template id="two">
<div class="twopage">
<p>我是第二个界面</p>
</div>
</template>
<script>
// 1.定义组件
const one = {
template: "#one",
};
const two = {
template: "#two"
};
// 2.定义切换的规则(定义路由规则)
const routes = [
// 数组中的每一个对象就是一条规则
{ path: '/one', component: one },
{ path: '/two', component: two }
];
// 3.根据自定义的切换规则创建路由对象
const router = new VueRouter({
routes: routes
});
// 这里就是MVVM中的View Model
let vue = new Vue({
el: '#app',
// 4.将创建好的路由对象绑定到Vue实例上
router: router,
watch: {
// 可以通过watch监听路由地址的变化, 只要路由地址发生变化, 就会自动调用对应的回调函数
"$route.path": function (newValue, oldValue) {
console.log(newValue, oldValue);
}
}
</script>
</body>