动态计算属性名称

3zz*_*zzy 2 vue.js vuex vuejs2

computed: {

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

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

    [this.element.inputName]: { 
    },

}
Run Code Online (Sandbox Code Playgroud)

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

如何动态设置道具名称?

小智 5

您可以根据这篇文章动态添加计算属性,

动态生成计算属性

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

该属性的使用是有限的,不能在创建时编译的 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
  },
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这绝不是一个优雅的解决方案,但在 2020 年,这仍然非常棒。对于使用数组自遍历属性树的超级聪明的减速器来说,这是一个加分项。会偷一点点:) (2认同)