需求:系统顶部添加项目下拉框,顶部下拉框选项改变时其他模块下拉框同时改变。
1.开始进入系统的时候获取项目列表
页面调用接口
// 获取项目列表 store.dispatch("getProject").then(() => {});
store新建project.js
1 import { listProjectNoPage } from "@/api/system/project"; 2 3 const project = { 4 state: { 5 projectList: [], 6 projectId: "", 7 }, 8 9 mutations: { 10 SET_PROJECT_LIST: (state, projectList) => { 11 state.projectList = projectList; 12 }, 13 SET_PROJECT_ID: (state, projectId) => { 14 state.projectId = projectId; 15 }, 16 }, 17 18 actions: { 19 // 获取用户项目信息 20 getProject({ commit, state }) { 21 return new Promise((resolve, reject) => { 22 listProjectNoPage() 23 .then((res) => { 24 const dataList = res.data; 25 if (dataList.length > 0) { 26 const projectId = dataList[0].projectId; 27 const projectOptions = dataList.map((item) => { 28 return { 29 value: item.projectId, 30 label: item.projectName, 31 ...item, 32 }; 33 }); 34 commit("SET_PROJECT_ID", projectId); 35 commit("SET_PROJECT_LIST", projectOptions); 36 } 37 resolve(res); 38 }) 39 .catch((error) => { 40 reject(error); 41 }); 42 }); 43 }, 44 // 修改选中项目 45 changeProject({ commit }, data) { 46 commit("SET_PROJECT_ID", data); 47 }, 48 }, 49 }; 50 51 export default project;
2.系统顶部引入项目列表监听变化
html
1 <el-select v-model="sysProjectId" placeholder="请选择项目" filterable> 2 <el-option v-for="(item, index) in sysProjectList" :key="index" :label="item.label" :value="item.value" /> 3 </el-select>
js
1 import { mapGetters } from 'vuex' 2 computed: { 3 ...mapGetters([ 4 'sysProjectList', 5 ]), 6 sysProjectId: { 7 get () { 8 return this.$store.state.project.projectId 9 }, 10 set (val) { 11 this.$store.dispatch('changeProject', val) 12 } 13 } 14 },
3.各子模块引入vuex下的项目列表 项目id
html
1 <el-form-item label="所属项目" prop="projectId"> 2 <el-select v-model="queryParams.projectId" placeholder="所属项目" filterable clearable @change="handleQuery"> 3 <el-option v-for="(item, index) in sysProjectList" :key="index" :label="item.label" :value="item.value" /> 4 </el-select> 5 </el-form-item>
js
1 import { mapGetters } from 'vuex' 2 computed: { 3 ...mapGetters([ 4 'sysProjectId', 5 'sysProjectList', 6 ]), 7 }, 8 watch: { 9 sysProjectId (newVal, oldVal) { 10 // 系统顶部选中项目变化 11 this.queryParams.projectId = newVal 12 this.getList() 13 } 14 }, 15 created () { 16 this.queryParams.projectId = this.sysProjectId 17 this.getList(); 18 },
标签:SET,projectId,project,state,应用,commit,vuex From: https://www.cnblogs.com/wjian0916/p/17219081.html