programing

동적 계산 속성 이름

goodsources 2022. 11. 29. 21:48
반응형

동적 계산 속성 이름

computed: {

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

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

    [this.element.inputName]: { 
    },

}

에러가 발생합니다.Uncaught TypeError: Cannot read property 'element' of undefined

프로펠러 이름을 동적으로 설정하려면 어떻게 해야 합니까?

이 게시물에 따라 계산된 속성을 동적으로 추가할 수 있습니다.

즉시 계산된 속성을 생성합니다.

속성 이름 소스가 중첩되어 있고 (아마도) 비동기적이기 때문에 변경을 처리하려면 딥 워처가 필요합니다.

속성 사용은 제한되어 있습니다.작성 시 컴파일된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
  },
}

Vue 컴포넌트 옵션 오브젝트 작성 시 컴포넌트의 Vue 인스턴스가 아니기 때문에 (작성 전) 계산된 porperties나 기타 Vue 컴포넌트 속성(소품, 데이터 등)을 사용할 수 없습니다.

나도 같은 문제가 있었어, 아니면 차라리 이걸 하고 싶어...

<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 
    }
}

언급URL : https://stackoverflow.com/questions/53332250/dynamic-computed-property-name

반응형