/* vuex模块文件(form.js) */
import router from "../../router";
import request from "../../utils/request";
const state = {
step: {
payAccount: "123456"
}
};
const actions = {
async submitStepForm({ commit }, { payload }) {
await request({
url: "/api/form",
method: "POST",
data: payload
});
commit("saveStepFormDate", payload);
router.push("/form/step-form/result");
}
};
const mutations = {
saveStepFormDate(state, { payload }) {
state.step = { ...state.step, ...payload };
}
};
export default {
namespaced: true, //解决命名冲突(使用时需要备注模块名)
state,
actions,
mutations
};
注:不同模块注入时,会出现命名冲突问题,所以在导出模块时,要给导出对象添加 namespaced: true 属性,给每个模块标注了一个命名空间,在使用时需要加上所属模块名
/* 模块导入store (index.js) */
import Vue from "vue";
import Vuex from "vuex";
import form from "./modules/form";
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
modules: { //模块导入
form
}
});
/* vuex使用 */
<template>
<a-form :form="form">
<a-form-item
:label-col="formItemLayout.labelCol"
:wrapper-col="formItemLayout.wrapperCol"
label="付款账号"
>
<a-input
v-decorator="[
'payAccount',
{
initialValue: step.payAccount,
rules: [{ required: true, message: '请输入付款账号' }]
}
]"
placeholder="请输入付款账号"
/>
</a-form-item>
<a-form-item>
<a-button type="primary" @click="handleSubmit">
下一步
</a-button>
</a-form-item>
</a-form>
</template>
<script>
export default {
data() {
return {
formItemLayout: {
labelCol: { span: 4 },
wrapperCol: { span: 14 }
},
form: this.$form.createForm(this)
};
},
computed: {
step() {
return this.$store.state.form.step;
}
},
methods: {
handleSubmit() {
const { form, $router, $store } = this;
form.validateFields((err, val) => {
if (!err) {
$store.commit({
type: "form/saveStepFormDate",//指定对应命名空间
payload: val
});
$router.push("/form/step-form/confirm");
}
});
}
}
};
</script>
注:调用 mutations 中的 saveStepFormDate方法:
–>要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法,模块中需要制定对应的模块(空间名下的方法)
–>Action 通过 store.dispatch 方法触发