sourcecode

Vue 구성 요소에 메서드를 동적으로 추가하는 방법

copyscript 2022. 8. 7. 16:48
반응형

Vue 구성 요소에 메서드를 동적으로 추가하는 방법

서버로부터 데이터를 취득할 때, 예를 들면[{methodName:mothodValue},{methodName:mothodValue}]나는 동적 생성 방식을 원한다.

methods: {
  functionArray.forEach(function (item) {
    item.functionName:function () {
      item.functionValue;
    }
  })
}

그래서 이게 내 코드야

var componentName = Vue.component(componentName, {
  data: function () {
    return {
      value: value
    }
  },
  template: componentTemplate,
  methods:{
    functionArray.forEach(function (item) {
      item.functionName:function () {
        item.functionValue;
      }
    })
  }
})

예전 암호는

methods:{
  getValue : function(){
    getValue(this.value);
  }
}

가능할까요?

Vue 컴포넌트를 작성하기 전에 서버에서 데이터가 반환된 경우(Vue 컴포넌트 작성 후 메서드를 추가할 수 있는지 확실하지 않음), 다음과 같은 메서드 개체를 생성할 수 있습니다.

var methods = {};
functionArray.forEach(function (item) {
  methods[item.functionName] = item.functionValue;
});

오브젝트 리터럴에 코드를 채울 수는 없지만 빈 오브젝트 리터럴에 이와 같은 코드를 나중에 채울 수는 있습니다.


그런 다음 다음과 같이 컴포넌트에 넣을 수 있습니다.

var componentName = Vue.component(componentName, {
  // ..
  methods: methods
});

언급URL : https://stackoverflow.com/questions/51833213/how-to-add-methods-dynamically-to-vue-component

반응형