代码之家  ›  专栏  ›  技术社区  ›  eozzy

动态计算属性名称

  •  0
  • eozzy  · 技术社区  · 7 年前
    computed: {
    
        ...mapGetters(['getElements']),
    
        element() {
            return this.getElements(this.formId, this.sectionId, this.elementId);
        },
    
        [this.element.inputName]: { 
        },
    
    }
    

    引发错误: Uncaught TypeError: Cannot read property 'element' of undefined

    如何动态设置道具名称?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Hiram K. Hackenbacker    7 年前

    您可以根据本文动态添加计算属性,

    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
      },
    }
    
        2
  •  0
  •   elad frizi    7 年前

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