1、在store文件中创建文件

在自己创建的js中写入
import api from '../../https/api' //引入的是请求文件
export default {
namespaced: true, //命名空间
state: {
report: {}
},
//同步修改state的值
mutations: { //方法
//报表
setreports(state, data) {
state.report = data
console.log('111', state.report)
}
},
actions: { 请求
//异步提交mutation
//基于时间统计的折线图
async reports({ commit }) {
let res = await api.reports()
console.log(res, '1111111')
commit('setreports', res.data)
}
},
}
2、引入
2.1、在store的index.js文件中 引入自己创建的文件
在头部引用 在modules中声明
自带
import Vue from "vue";
import Vuex from "vuex";
引入
import Vue from "vue";
import Vuex from "vuex";
import user from './user/user'
import dataCount from './dataCount/dataCount'
import roles from './roles/roles'
import goods from './goods/goods'
import order from './order/order'
Vue.use(Vuex);
//
export default new Vuex.Store({
//存储共享的数据
state: {
tag1: [] //标签
},
//同步修改state的值
mutations: {},
//异步提交mutation
actions: {},
//模块
modules: {
user, 声明
dataCount,
roles,
goods,
order,
}
});
3、使用
1、在
script中引用
2、在
methods中引用方法
3、在
mounted或自己要引用该方法的地方使用eg:this.addGoods()
如:
this.addGoods()
4、在
computed中引用变量 在渲染处可直接使用
<script>
//在组件中引用
import { createNamespacedHelpers } from "vuex";
const userModule = createNamespacedHelpers("goods"); //goods模块名
const { mapActions, mapState } = userModule;
export default {
name: "",
props: {},
components: {},
data() {
return {}
},
methods: {
...mapActions(["upload", "addGoods"]), //声明方法
},
mounted() {
this.upload()//方法的使用
变量可以直接渲染
},
watch: {},
computed: {
...mapState(["picData"])//声明变量
}
};
</script>