2016-09-07 42 views
1

我想擴展方法。示例:VueJS擴展方法和數據

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

我使用多個擴展。

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

錯誤代碼: this.fetchData未定義。 this.modal不是函數

+0

'extend'用於創建組件。從你的代碼我沒有看到任何組件。 – highFlyingDodo

回答

2

Vue.extend返回一個新的Vue組件定義,該定義稍後可以使用new關鍵字實例化,它不會更改全局Vue對象。所以,如果你想創建一個組件層次的嘗試:

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() 

檢查出fiddle一個活生生的例子。

+0

謝謝你美麗的解決方案 –