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也会自动更新。

posted @ 2022-03-23 01:37  菜鸟小何  阅读(248)  评论(0编辑  收藏  举报