Cesur APAYDIN
Cesur APAYDIN

Reputation: 836

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

Upvotes: 2

Views: 7719

Answers (1)

pkawiak
pkawiak

Reputation: 1339

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.

Upvotes: 2

Related Questions