动态计算的属性名称

时间:2018-11-16 05:59:47

标签: vue.js vuejs2 vuex

computed: {

    ...mapGetters(['getElements']),

    element() {
        return this.getElements(this.formId, this.sectionId, this.elementId);
    },

    [this.element.inputName]: { 
    },

}

抛出错误:Uncaught TypeError: Cannot read property 'element' of undefined

如何动态设置道具名称?

3 个答案:

答案 0 :(得分:1)

您可以按照这篇文章动态添加计算属性

Generating computed properties on the fly

由于属性名称源是嵌套的(并且可能是异步的),因此您将需要深入的观察者来处理更改。

该属性的使用受到限制,您不能在创建时编译的SFC模板上使用它。在方法中使用它时,您可能需要根据调用顺序检查它的存在。

computed: {
  element() {
    return this.getElements(...);
  },
},
watch: {
  element: {
    handler: function (newValue) {
      if (newValue.inputName) {
        this.addProp(['element', 'inputName'], () => { return 'someValue' })
      }
    },
    deep: true
  }
},
methods: {
  addProp (path, getter) {
    // Get property reference or undefined if not (yet) valid
    const propName = path.reduce((acc, prop) => acc ? acc[prop] : undefined, this)
    if (!propName) { return }

    const computedProp = {
      get() {
        return getter()
      }
    }
    this[propName] = computedProp
  },
}

答案 1 :(得分:0)

在创建Vue组件选项对象时,您不是组件的Vue实例(在创建之前),因此您无法使用计算的性能或其他Vue组件属性(道具,数据)等等 ...)

答案 2 :(得分:0)

我遇到了同样的问题,或者想让我这样做...

<script>
export default {
  data: {
    return: {
      init: 0
    }
  },
computed: {
    makeComputed() { 
init++ // call something in data to fire the computed function  
      Object.assign(this, ...this.$store.state.auth.objectwithmanyprops)
      return this.$store.state.auth.objectwithmanyprops 
    }
}