<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
姓: <input type="text" v-model="firstname"><br/>
名: <input type="text" v-model="lastname"><br/>
姓名1: <span>{{fullname1}}</span><br/><!--使用计算属性-->
姓名2: <span>{{fullname2}}</span><br/><!--使用watch-->
姓名3: <span>{{fullname3}}</span><!--使用vm实例上的watch方法-->
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
firstname: '',
lastname: '',
fullname2: '',
fullname3: ''
},
computed: {// 使用计算属性,计算fullname1的值
fullname1: function(){
return this.firstname+' '+this.lastname
}
},
watch: {// 使用watch监视fullname1,并更新fullname2的值
fullname1: function(newValue, oldValue){
this.fullname2 = newValue
}
}
})
// 使用vm实例上的watch方法,监视fullname2的值,并更新fullname3的值
vm.$watch('fullname2', function (newValue, oldValue) {
this.fullname3 = newValue
});
</script>
</body>
</html>