computed的setter妙用
使用场景:当我们用v-model绑定了一个计算属性,想直接设置计算属性时,就要利用到setter
demo:
<template> <div> <div>First Name: <el-input v-model="firstName" placeholder="请输入内容"></el-input> </div> <div>Second Name: <el-input v-model="secondName" placeholder="请输入内容"></el-input> </div> <div>Full Name: <el-input v-model="fullName" placeholder="请输入内容"></el-input> </div> </div> </template>
export default{ data () { return { firstName: '', secondName: '' } }, components: {}, computed: { fullName: { get: function () { return this.firstName + ' ' + this.secondName }, set: function (newVal) { let names = newVal.split(' ') this.firstName = names[0] this.secondName = names[1] } } } }
实现的效果:firstName 、secondName 发生变化,fullName会自动更新;反过来,fullName的改变,firstName 和 secondName也会自动更新。
长风破浪会有时,直挂云帆济沧海