<template>
<div>
<h1>計算屬性和監聽屬性</h1>
<!--表達式太復雜會導致難以維護,而且如果多個地方使用該表達式會導致重復-->
<div>
{{type + "" +msg}}
</div>
<!--使用computed計算屬性-->
<div>{{type_msg}}</div>
<hr>
<div>{{firstName}}</div>
<div>{{lastName}}</div>
<div>{{fullName}}</div>
<button @click="modifyFullName">修改fullName</button>
</div>
</template>
<script>
export default {
name: "demo7",
data(){
return {
type:"news",
msg:"demo7",
firstName:"zhang",
lastName:'sanfeng'
}
},
computed:{
type_msg(){
return this.type + ':' + this.msg
},
// fullName() {
// return this.firstName +":"+this.lastName
// }
fullName: {
get(){
return this.firstName +":"+this.lastName
},
set(newVal){
console.log(newVal)
let arr= newVal.split(" ");
this.firstName = arr[0];
this.lastName = arr[1];
}
// return this.firstName +":"+this.lastName
}
},
methods:{
modifyFullName(){
this.fullName ="xiao ming"
}
}
}
</script>
<style scoped>
</style>
點擊修改fullName按鈕觸發set方法,參數newVal接受的就修改后fullName值
效果圖:

