【问题标题】:How to use Vuex store in a plugin如何在插件中使用 Vuex 商店
【发布时间】:2021-01-14 03:50:06
【问题描述】:

我有一个自定义的 Vue 插件,它有一个自定义的实例方法

import Echo from 'laravel-echo';
import Vue from 'vue';
import config from '@/config';

const echor = {
    install(Vue){
        Vue.prototype.$echo = options => {
            return new Echo({
                // how can I get store value inside an instance methods?
                auth: {
                    headers: {
                        Authorization: `${store.state.auth.token.token_type} ${store.state.auth.token.access_token}`
                    }
                }
            });
        }
    }
};

Vue.use(echor);

如何在实例方法中获取存储值以使 Authorization 标头有效?我用谷歌搜索,但没有任何帮助。

非常感谢!

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    您可以在插件的 install 方法中添加额外的 store 参数:

    install(Vue, store){
    ...
    }
    

    您的插件的使用者会这样称呼您的插件:

    import echor from '@/echor';  // or however you distribute it
    import store from '@/store';  // user's own store
    
    Vue.use(echor, store);
    

    您可以通过这种方式向安装函数添加任意数量的附加参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 2021-12-05
      • 2021-07-22
      • 2017-12-18
      • 2019-04-28
      • 1970-01-01
      • 2020-01-10
      相关资源
      最近更新 更多