我在哪里可以使用调度Vuex操作的全局方法?我创建了一个Vuex模块"simplert",其中包含一些显示simplert的函数 . 我已经创建了一个HTML文件,我将其放在单个simplert中
<simplert :use-radius="true"
:use-icon="true"
ref="simplert">
</simplert>
我用它来通过商店模块的功能显示一些简单的消息(信息,警告,错误等) . 这是我的模块:
/* eslint-disable no-shadow */
/**
* Vuex Module to control the component Simplert
*/
import { trans } from '../../plugin/translation';
// initial state
function initialState() {
return {
title: '',
message: '',
type: 'info',
customClass: 'simplert-popup',
customIconUrl: '',
customCloseBtnText: trans('close'),
customCloseBtnClass: 'btn btn-primary',
useConfirmBtn: false,
customConfirmBtnText: trans('confirm'),
customConfirmBtnClass: 'btn btn-success',
disableOverlayClick: '',
hideAllButton: false,
showXclose: true,
onOpen: null,
onConfirm: null,
onClose: null,
};
}
// state
const state = initialState();
// mutations
const mutations = {
show(state, simplert) {
simplert.openSimplert(state);
},
reset(state) {
const s = initialState();
Object.keys(s).forEach((key) => {
state[key] = s[key];
});
},
setData(state, data) {
Object.keys(data).forEach((key) => {
state[key] = data[key];
});
},
};
// actions
const actions = {
reset({ commit }) {
return new Promise((resolve) => {
commit('reset');
resolve();
});
},
show({ dispatch, commit }, { alert, data }) {
dispatch('reset').then(() => {
commit('setData', data);
commit('show', alert);
});
},
showInfoAlert({ dispatch }, { alert, title, message }) {
const data = {
title,
message,
type: 'info',
};
dispatch('show', { alert, data });
},
showSuccessAlert({ dispatch }, { alert, title, message }) {
const data = {
title,
message,
type: 'success',
};
dispatch('show', { alert, data });
},
showErrorAlert({ dispatch }, { alert, title, message }) {
const data = {
title,
message,
type: 'error',
};
dispatch('show', { alert, data });
},
showWarningAlert({ dispatch }, { alert, title, message }) {
const data = {
title,
message,
type: 'warning',
};
dispatch('show', { alert, data });
},
};
export default {
namespaced: true,
state,
mutations,
actions,
};
现在我想创建一个使用“showErrorAlert”操作的全局方法来显示来自Promise的错误 . 所以为了调度动作我使用这个简单的代码:
app.$store.dispatch('simplert/showErrorAlert', {
alert: app.$refs.simplert,
title: app.$trans('simplert_error_title'),
message: response.body,
});
但是我希望在函数中使用该代码可以轻松地从我的组件调用 . 我该怎么说呢?在我的vue实例中(但不是从指南推荐)或插件内部(mixin或方法?)
1 回答
我认为我找到了管理这种情况的正确方法 . 我删除了商店模块的“simplert”,并将其功能复制到了mixin中 . 所以我在mixin的文件夹里面创建了一个simplert.js文件,在那里我把所有的逻辑都用来管理简单的警报 . 然后在我的组件中,我在需要时导入了mixin . 通过这种方式,我简化了simplert的管理,我只在需要它的组件中使用它