Search code examples
vue.jsvue-resourcevue-component

VueJS Extends Methods and Data


I would like to extend methods. Example:

Vue.extend({
    data: function () {
        return {
            fetcData: 'Test',
        }
    },
    methods: function(){
        return {
            modal: function(){ alert('Modal') },
        }
    }
});
Vue.extend({
    ....
});

I use multiple extends.

// VueJS Instance
new Vue({
    el: 'html',
    data: {
        effect: true
    },
    methods: {
        xhrGet: function () {
            alert(this.fetcData); // Undefined
            this.modal(); // Undefined
        },
        xhrPost: function (event) {
            alert('xhrPost')
        }
    }
});

Error Code: this.fetchData is undefined. this.modal is not a function


Solution

  • Vue.extend returns a new Vue component definition that can be later on instantiated using new keyword, it doesn't change the global Vue object. So if you want to create a component hierarchy try:

    var BaseComponent = Vue.extend({
      methods: {
        foo: function() { console.log('foo') }
      }
    })
    
    var MyComponent = BaseComponent.extend({
      methods: {
        bar: function() { 
          this.foo()
          console.log('bar')
        }
      }
    })
    
    let myComponentInstance = new MyComponent()
    

    Check out that fiddle for a live example.