computed 的get()执行的时机:页面加载/computed里面相关属性发生变化
//这个计算属性(函数)需要一个返回值作为函数的结果
计算属性名不能是data里面的属性名
watch:属性名就是要监听的属性名,属性发生变化就执行
watch 监听的属性发生改变,直接更新数据
computed
get() 读取当前属性值 根据相关属性 计算并返回当前属性的值【】
//get() 监听了更多的属性 其中一个发生变化 就执行get()
//监视当前计算属性的变化 也就是get的return的值发生变化
set(newValue){
}
也就是说,变化的是get里面的元素,发生的是get()
发生变化的不是get里面的元素,而是这个属性值直接发生变化
计算属性 | watch |
---|---|
get()监听多个属性 | 监听单个属性 |
set()可以监听当前计算属性值的变化,set()的变化如果不让get()里面的因素变化,就不会触发get(),修改了get里面的因素就会触发get() | |
get()是有缓存的,避免重复计算 |
<!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">
<title>Document</title>
<script src="../VUE/vue.js"></script>
<style>
img {
height: 100px;
}
.box {}
</style>
</head>
<body>
<div class="box">
firstName<input type="text" v-model="firstName"><br>
lastName<input type="text" v-model="lastName"><br>
computed<input type="text" v-model="fullName"><br>
watch<input type="text" v-model="fName_w"><br>
<!-- {{fullName}}
{{fullName}}
{{fullName}} -->
</div>
</body>
<script>
const vm = new Vue({
el: ".box",
data: {
firstName: "A",
lastName: "B",
fName_w:"A B",
count:0
},
computed: {
fullName:{
get() {
console.log("fullName",this.count++)
return this.firstName +" "+ this.lastName;
//return 是 fullName的值
},
set(newVal) {
this.firstName = newVal.split(" ")[0];
this.lastName = newVal.split(" ")[1];
}
}
},
watch:{
firstName(val){
this.fName_w = val +" " +this.lastName ;
},
lastName(val){
this.fName_w = this.firstName + " "+val;
}
}
})
</script>
</html>
<!--
{{msg}}
{{*msg}}
{{{msg}}}
-->