Search code examples
vuejs2vue-component

How to add methods dynamically to Vue component


When I get data from the server, like [{methodName:mothodValue},{methodName:mothodValue}] then I want dynamic generation method, like

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

so this is my code

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

the old code was

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

Is that possible?


Solution

  • If the data from the server is returned before the creation of the Vue component (I'm not sure if you can add methods after the creation of a Vue component), then you can create a methods object like so:

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

    You can't populate an object literal with code, but you can populate an empty object literal afterwards with code like so.


    Then you can put it into your component like so:

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