1、vuex的作用:
vuex用来做状态管理。它可以将vue项目里面一些全局变量存放在vuex。可以简单的理解为项目的全局变量,但是值得注意的是Vuex里面的数据只要页面刷新就会丢失了。
在DM项目中的使用就是保存一些全局的缓存数据,这样就可以实现组件之间的数据共享。
2、主要组成部分:
- 状态 state:这里存放全局变量,组件访问这里面的数据时,可通过 this.$store.state.属性名 访问
- 状态更改 mutations:这里存放的是对 state中 数据更改的方法,需要在 actions 的方法通过commit函数来触发
- 执行操作 actions:
因为在mutations中不能编写异步的代码,会导致vue调试器的显示出错。所以在vuex中我们可以使用Action来执行异步操作,存放的是一些异步操作的方法。通过调用这些方法间接变更state中的数据。
组件在其methods中的方法通过调用dispatch函数,以此触发actions中的方法:
this.$store.dispatch('方法名')
3、使用:
一般都是在组件中来访问state中的全局变量,在页面进行展示,所以通常在组件的 methods中的一个方法 或created() 通过调用this.$store.dispatch('方法名')来执行actions中的方法,这样就可以对state中的数据进行更新,然后通过 computed 属性来监听state中的数据,最后就是拿到 computed 属性中对应的数据在对应的位置上进行展示。
执行流程大致为:
methods-->actions-->mutations-->state
注:一定要在 computed 属性中监听,否则数据将不准确。
4、代码示例:
global.js:
import global from '../../api/global'
const state = {
deviceTypeList: [],
projectList: [],
}
const mutations = {
setDeviceTypeList: (state, data) => {
state.deviceTypeList = data
},
setProjectList: (state, data) => {
state.projectList = data
}
}
const actions = {
setDeviceTypeList({ commit }) {
return global.deviceType().then(res => {
if (res.code == 200) {
commit('setDeviceTypeList', res.data)
}
}).catch(err=>{
})
},
setProjectList({ commit }) {
return global.project().then(res => {
if (res.code == 200) {
commit('setProjectList', res.data)
}
}).catch(err=>{
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
index.vue:
<template>
<div class="addLinkData">
<div class="content_box">
<div class="content">
<el-form :inline="true" :model="queryData" class="demo-form-inline">
<el-form-item label="设备编号" label-width="100px">
<el-input
class="input_item"
v-model="queryData.deviceCode"
placeholder="设备编号">
</el-input>
</el-form-item>
<el-form-item label="设备名称" label-width="100px">
<el-input
class="input_item"
v-model="queryData.deviceName"
placeholder="设备名称">
</el-input>
</el-form-item>
<el-form-item label="设备类型" label-width="100px">
<el-select
clearable
class="filter_item"
v-model="queryData.deviceTypeUuid"
placeholder="设备类型"
>
<el-option
v-for="item in deviceTypeList"
:key="item.uuid"
:label="item.uuid"
:value="item.uuid"
>
</el-option>
</el-select>
</el-form-item>
</el-form>
</div>
</div>
</template>
<script>
import ContentHeader from "@/components/ContentHeader";
import Drawer from "@/components/Drawer";
import Pagination from "@/components/Body/Pagination";
import project from "@/api/project";
import device from "@/api/device";
export default {
props: ["uuid"],
created() {
this.listRelationDevice();
this.$store.dispatch("global/setDeviceTypeList");
},
computed: {
deviceTypeList() {
return this.$store.state.global.deviceTypeList;
},
},
components: {
ContentHeader,
Drawer,
Pagination
},
data() {
return {
reqData: {
pageSize: 50,
pageIndex: 1,
projectUuid: this.uuid
}
};
},