<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值
效果图: