2017-08-27 78 views
1

我是使用Vue的新手。我正在試圖圍繞插件。使用Vue插件

組件:Rest.vue

... 
export default { 
    name: 'rest', 
    data() { 
    return { 
    } 
    }, 

    methods: { 
     gplFetch: function(query){ 
    ... 
    return ...; 
     } 
    } 
} 
... 

插件:全局插件

import Rest from ‘@/components/Rest.vue’ 

export default { 

install(Vue, options) { 

    Vue.component(Rest.name, Rest)  

    Vue.mixin({ 
    created() { 
     console.log('rest created'); 
    } 
    }) 

    Vue.prototype.$gplFetch = function(query){ 

    return <Access Rest component>.gplFetch(query); 
    } 
    } 
} 

用什麼,我被困在使用組件及其方法,我添加到我的插件main.js

import GlobalPlugin from '@/plugins/global-plugin.js' 

Vue.use(GlobalPlugin); 

卻困在什麼是如何在上面的代碼中訪問gplFetch:

return <Access Rest component>.gplFetch(query); 

回答

1

爲了使代碼工作的回報應該是

return Rest.methods.gplFetch(query); 

不過,我會建議採取不同的方法,並創建包含gplFetch功能的模塊(或者是一個API模塊)和將該方法導入您的插件和Rest.vue組件。

gplFetch.js

export function gplFetch(query){ 
    // do something with query 
} 

Rest.vue

import {gplFetch} from "./gplFetch.js" 

export default { 
    name: 'rest', 
    data() { 
    return { 
    } 
    }, 
    methods: { 
    gplFetch 
    } 
} 

全球plugin.js

import {gplFetch} from "./gplFetch.js" 

export default { 

    install(Vue, options) { 

    Vue.component(Rest.name, Rest)  

    Vue.mixin({ 
    created() { 
     console.log('rest created'); 
    } 
    }) 

    Vue.prototype.$gplFetch = function(query){ 

     return gplFetch(query); 
    } 
    } 
} 

賽道的這e,所有假設gplFetch不依賴於Rest.vue實例中的任何數據,因爲如果它確實是,它首先不會從您的插件工作。

+0

非常感謝。你提供了一個解決方案,但你也提供了一個我決定採用的更好的解決方案。你太棒了 :) – adviner