Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
There are several options here:
The option is quite bad: we drag Vuex behind our plugin, we connect it ourselves, we make our own store - profit. The only plus is that it's easy to implement. The bad news is that the user of your plugin won't be able to interact with its state if they want to. Also, if your version of Vuex differs from the version of the user, then the user will have 2 times in the vuex bundle.
A better option: we strictly require the user to give us his store in the options for the plugin, and inject our module into his store. You can also specify vuex in the peerDependencies of our package.json
Pros: we use the user's Vuex, rather than dragging our own; let the user interact with the state of the plugin.
Cons: clog the user's store, regardless of his desire; if the user does not need a store, he will still be forced to create it
Good option: we give the user the option to give us his store, and if not, we create our own.
Minus: confusing in the implementation
Plus: freedom of action for the user, from the mandatory actions - only install Vuex
In any case, it's best to keep your state in a separate Vuex module You
can read about modules here: https://vuex.vuejs.org/ru/guide /modules.html
Well, how to implement a good option, I'll show you an example:
import Vuex from 'vuex';
import pluginStoreConfig from './store';
const PLUGIN_NAME = 'MyPlugin';
let Vue; // подключим из install
// наш плагин
export default {
install(_Vue, options = {}) {
Vue = _Vue;
let {store} = options;
if(store) {
// если передали store - регистрируем в нем свой модуль
store.registerModule(PLUGIN_NAME, pluginStoreConfig);
} else {
// не передали, для начала проверим, установлен ли Vuex в Vue
if(!new Vue({store: {}}).$store) {
// и если нет, установим
Vue.use(Vuex);
}
// и создадим новый store с единственным модулем - нашим
store = new Vuex.Store({modules: {
[PLUGIN_NAME]: pluginStoreConfig
}});
}
// немного упростим себе жизнь, чтоб не писать каждый раз наш нэймспейс
// если что-то не используется, то можно убрать
const boundStore = {
state: store.state[PLUGIN_NAME],
getters: store.getters[PLUGIN_NAME],
commit(mutation, payload, options) {
return store.commit(`${PLUGIN_NAME}/${mutation}`, payload, options);
},
dispatch(action, payload, options) {
return store.dispatch(`${PLUGIN_NAME}/${action}`, payload, options);
},
watch(fn, cb, options) {
return store.watch((state, getters) => fn(state[PLUGIN_NAME], getters[PLUGIN_NAME]), cb, options);
}
};
// дальше творим прочую магию нашего плагина
// ...
}
};
export default {
namespaced: true,
state: {/* ... */},
getters: {/* ... */},
actions: {/* ... */},
mutations: {/* ... */}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question