首页 > 解决方案 > 具有 20 多个属性的双向计算属性 (get,set)

问题描述

我有一个包含 20 多个属性的组件,我想将这些属性转换为如下所示的双向计算机属性。问题是这些属性的唯一列表很长(实际上是 28 个),因此转换所有属性将非常重复,并且会占用大量不必要的空间。有什么我不知道的技巧可以让它看起来干净吗?

   computed: {
       exp: {
          get () {
             return this.job.exp
          },
          set (value) {
             this.$emit('job', { exp: value })
          }
       },

       fund: {
          get () {
             return this.job.fund
          },
          set (value) {
             return this.$emit('job', { fund: value})
          }
       },
       // more to come
    }

this.$emit('job', arg)发出时使用的以下方法:

updateJob (object, source) {
      for(const [key, value] of Object.entries(object)){

        this.job[key]
          ? this.job[key] = value
          : this.$set(this.job, key, value)
      }
    },

标签: javascriptvue.js

解决方案


您可以将$watchapideep: true选项一起使用。这是一个带有增量函数的基本实现:

new Vue({
  el: "#app",
  data: {
    job: {
      a: 11,
      b: 22,
      c: 33,
      d: 44,
      e: 55,
      f: 66,
      g: 77,
      h: 88,
      // ...
    },
  },
  created() {
    // use $watch interface with the deep option
    this.$watch('job', (newVal, oldVal) => {
      // check for changes from the previous state
      Object.keys(newVal).forEach(key => {
        if(newVal[key] !== oldVal[key]) {
          console.log('changed job attr', key, newVal[key])
          this.$emit('job', {[key]: newVal[key]})
        }
      })
    }, {deep: true})
  },
  methods: {
    increment(key) {
      // needs to be reassigned rather than mutated if you want
      // the $watch callback to get the correct oldVal
      const val = this.job[key] + 1
      this.job = Object.assign({}, this.job, {[key]: val})
    }
  },
})

html来演示增量函数:

<div id="app">
  <ul>
    <li v-for="(val, key) in job" :key="key" @click="increment(key)">
      {{ key }}: {{ val }}
    </li>
  </ul>
</div>

推荐阅读