vm實例
中的watch
屬性凭涂,是用來監(jiān)視數(shù)據(jù)的改變的,他是個對象救赐,里面定義函數(shù)涧团,函數(shù)名就是數(shù)據(jù)名,這個函數(shù)接收兩個參數(shù)newVal
和oldVal
经磅,一個代表新數(shù)據(jù)泌绣,一個代表舊數(shù)據(jù),當(dāng)數(shù)據(jù)發(fā)生改變的時候预厌,就會觸發(fā)這個函數(shù)阿迈。
例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model='firstName'>+
<input type="text" v-model= 'lastName'>=
<input type="text" v-model='fullName'>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName:'',
lastName:'',
fullName:''
},
methods: {},
watch: {
firstName:function(newVal, oldVal) {
this.fullName = newVal + this.lastName;
},
lastName: function(newVal, oldVal) {
this.fullName = this.firstName + newVal;
}
}
});
</script>
</body>
</html>
watch的牛逼之處,在于他可以監(jiān)視一些非Dom元素轧叽,比如路由苗沧,看下面的例子:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="js/vue.js"></script>
<script src="js/vue-router-3.0.1.js"></script>
</head>
<body>
<div id="app">
<router-link to="/login">登陸</router-link>
<router-link to="/register">注冊</router-link>
<router-view></router-view>
</div>
<script>
var login = {
template: '<h1>這是登陸頁面</h1>'
}
var register = {
template: '<h1>這是注冊頁面</h1>'
}
var router = new VueRouter({
routes:[
{path: '/', redirect: '/login'},
{path: '/login', component: login},
{path: '/register', component: register}
]
})
var vm = new Vue({
el: '#app',
data: {},
methods: {},
router,
watch: {
'$route.path': function(newVal, oldVal) {
if(newVal == '/login') {
console.log('歡迎進(jìn)入登陸界面')
}else if(newVal == '/register') {
console.log('歡迎進(jìn)入注冊頁面')
}
}
}
});
</script>
</body>
</html>