关于计算属性
案例:分别输入姓和名,打印全名
基本代码
<div id='root'>
first name<input type="text" v-model="firstname"><br/><br/>
last name<input type="text" v-model="lastname"><br/><br/>
fullname: <span>???</span>
</div>
<script type="text/javascript">
new Vue({
el: "#root",
data: {
firstName: "Aisen",
lastName: "Rowell"
}
})
</script>
- 使用插值语法
fullname: <span>{{firstname}} - {{lastname}}</span>
- methods属性
fullname: <span>{{fullname()}}</span>
vue对象配置
<!---vue instance--->
<script type="text/javascript">
new Vue({
el: "#root",
data: {
firstName: "Aisen",
lastName: "Rolwell"
},
methods: {
fullname(){
return this.firstname + '-' + this.lastname
}
},
})
</script>
当然也可以使用计算属性
计算属性
读取的属性需要通过已有的属性计算得来
fullname: <span>{{fullname()}}</span>
<!---vue instance--->
<script type="text/javascript">
const v = new Vue({
el: "#root",
data: {
firstName: "Aisen",
lastName: "Rowell"
},
computed: {
fullname: {
// getter was called when fullname was read
// return a value as fullname
get() {
console.log("getter called.")
return this.firstname + '-' + this.lastname
}
// setter was called when the value was changed
set(value) {
console.log("value changed")
const arr = value.split('-')
this.firstname = arr[0]
this.lastname = arr[1]
}
}
},
})
</script>
简写: 只有当只读取数据的情况时,即setter被忽略
fullname: <span>{{fullname}}</span>
<!---vue instance--->
<script type="text/javascript">
const v = new Vue({
el: "#root",
data: {
firstName: "Aisen",
lastName: "Rowell"
},
computed: {
// 完整写法
/*fullname: {
// getter was called when fullname was read
// return a value as fullname
get() {...}
// setter was called when the value was changed
set(value) {...}
}*/
// 简写,注意这不是函数,而是读取数值时对应的getter方法简写
fullname(){
console.log("getter called.")
return this.firstname + '-' + this.lastname
}
},
})
</script>
比较methods属性
优势:存在缓存机制,可以复用。使用计算属性,重复读取某一值时,实际只调用一次;methods属性则需要每次调用方法
监视属性
监视属性中的对象一旦发生变化,对象中的方法会被调用,更新前后的值也会被记录
❗被监视的属性必须存在才能成功监视 ❗ 包括那些来自data属性和computed属性
new Vue({
// ...
watch: {
// value to be watched, was initialied in data property
isDone: {
immediate: true, // 初始化时就调用一次handler
// handler was called when isDone is changed
handler(newValue, oldValue){
console.log("isDone is changed to ", oldValue)
}
}
}
})
深度监视
写在前面