vue实例之watch

一 概念

- 监听器:watch

```html
<div id='app'>
    <div>
        姓名:<input type='text' v-model='full_name'>
    </div>
    <p>姓:{{ first_name }}</p>
    <p>名:{{ last_name }}</p>
</div>
<script>
    new Vue({
    	el: '#app',
    	data: {
    		full_name: '',
            first_name: '',
            last_name: ''
    	},
        watch: {
            full_name: function() {
            	this.first_name = this.full_name.split(' ')[0];
                this.last_name = this.full_name.split(' ')[1];
        	}
        }
    })
</script>
```

二 代码示范

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>watch</title>
</head>
<body>
<div id="app">
<div>
<label>姓名:</label>
<input type="text" v-model="full_name">
</div>
<p>姓: {{ first_name }} </p>
<p>名: {{ last_name }} </p>
</div>
</body>
<script src="js/vue-2.5.17.js"></script>
<script type="text/javascript">
// 多个变量依赖于一个变量, 对该变量进行监听
new Vue({
el: "#app",
data: {
full_name: "",
first_name: "",
last_name: ""
},
// 监听full_name变量,通过full_name具体修改first_name,last_name
watch: {
full_name () {
var fullName = this.full_name;
console.log(fullName);
this.first_name = fullName.split(" ")[0];
this.last_name = fullName.split(" ")[1];
}
}
})
</script>
</html>

 

posted @ 2018-10-29 19:39  不沉之月  阅读(364)  评论(0编辑  收藏  举报