<!DOCTYPE html>
<html lang="en">
<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">
<script type="text/javascript" src="../js/vue.js"></script>
<title>监视属性5姓名案例_watch实现.</title>
</head>
<body>
<!--
computed和watch之间的区别
1.computed能完成的,watch一定能完成
两个重要原则
所有被vue管理的函数最好都写成普通函数,这样this才能指向vue或者组件实例对象
所有不被vue管理的函数,如ajax的回调函数,定时器函数等,最好写成箭头函数,这样this才能指向vue或者vue的组件实例对象
-->
<div id="root">
姓 <input type="text" v-model="firstNam" ><br>
名 <input type="text" v-model="lastName"><br>
全名 <span>{{fullName}}</span>
</div>
<script>
const vm=new Vue({
el: "#root",
data: {
firstNam: "张",
lastName:"三",
fullName:'张-三'
},
computed:{
/* fullName:{
//当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
//初次读取fullName会被调用get ,所依赖的数据发生变化的时候get也重新调用
get(){
return this.firstNam+"-"+this.lastName;
},
//set当fullName被修改时
set(value){
const arr=value.split("-");
this.firstNam=arr[0];
this.lastName=arr[1];
}
} */
},
watch:{
firstNam(newValue,oldValue){
this.fullName=newValue+'-'+this.lastName;
},
lastName(newValue, oldValue) {
this.fullName = this.firstNam + '-'+ newValue;
},
}
})
</script>
</body>
</html>