【Vue】计算属性getter、setter

1,807 阅读1分钟

image.png

今天刚好复习到Vue的计算属性,自己试验的时候有了一些思考,记录总结下:

  1. get根据get中变量的变化而变动;
  2. set是根据计算属性值的直接更改而变动;

1. get根据get中变量的变化而变动;

这一点其实蛮好理解的,先上代码。

  computed:{
    // 最基础的计算属性用法,默认只有getter
    fullName(){
      return this.lastName + ' ' + this.firstName
    },    
  },

最基础的计算属性用法,默认只有getter,此时只要变量lastName、firstName中有一个发生变化,那么fullName就会根据这两个变量的变化而变动;

2. set根据计算属性值的变化而变动;

  computed:{
    // 计算属性的getter、setter
    fullName:{
      get(){
        console.log('调用了getter属性')
        return this.lastName + ' ' + this.firstName
      },
      set(value){
        console.log('调用了setter属性',value)        
        console.log(value)
      }
    }
  },

setter这个属性我原本的理解是监听计算属性值变化后触发的方法。那么lastName、firstName值变化带动fullName的变化时,也应该执行set里面的内容...

    change(){      
      var name = this.nowName.split(' ')      
      this.lastName = name[0]
      this.firstName = name[1]
    }

结果并没有触发set中的内容并没有输出"调用了setter属性",

image.png

image.png

image.png

image.png

直接改动fullName的值,才执行set中的内容

    change(){      
       this.fullName = this.nowName
    }

image.png

image.png

image.png

image.png

最后,附上完整代码:

<template>
  <div class="test" style="padding: 20px">
    <input type="text" v-model="nowName" />
    <button @click="change">改名</button>
    {{ fullName }}
  </div>
</template>

<script>
export default {
  name: 'test',
  data() { 
    return {
      firstName:"国庆",
      lastName:"王",
      nowName:""
    }
  },
  computed:{
    // 最基础的计算属性用法
    // fullName(){
    //   return this.lastName + ' ' + this.firstName
    // },
    // 计算属性的getter、setter
    fullName:{
      get(){
        console.log('调用了getter属性')
        return this.lastName + ' ' + this.firstName
      },
      set(value){
        console.log('调用了setter属性',value)        
        console.log(value)
      }
    }
  },
  methods:{
    change(){      
      // var name = this.nowName.split(' ')      
      // this.lastName = name[0]
      // this.firstName = name[1]
      this.fullName = this.nowName
    }
  },
 }
</script>

<style lang="scss" scoped>
</style>