2017-08-27 77 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