2017-09-25 80 views
1

下面是一個例子:如何訪問函數內從組件生命週期方法混入的方法Vue.js

mixin.js

export default { 
    methods : { 
     aFunction() { // Some functionality here } 
    } 
} 

component.vue

import mixin from './mixin' 
export default { 
    mixins : [ mixin ] 
    created() { 
     // Call aFunction defined in the mixin here 
    } 
} 

我想通過組件內部的created()生命週期方法訪問mixin內部定義的aFunction。

回答

5

的混入方法被合併與組件的當前實例,所以這純粹是:

created(){ 
    this.aFunction() 
} 

下面是一個例子。

console.clear() 
 

 
const mixin = { 
 
    methods:{ 
 
    aFunction(){ 
 
     console.log("called aFunction") 
 
    } 
 
    } 
 
} 
 

 
new Vue({ 
 
    mixins:[mixin], 
 
    created(){ 
 
    this.aFunction() 
 
    } 
 
})
<script src="https://unpkg.com/[email protected]"></script>

+0

出於某種原因,該函數被調用的3倍? –

+0

@ gaurav4sarma在哪裏?這裏叫它一次。在你的代碼中,如果這個組件被創建了多次。 – Bert

+0

是的,可能就是這樣。如何構造它的流程只能被調用一次我的意思是有一種方法可以使它只調用一次,因爲它調用一個API來獲取數據 –

相關問題