1、main.js引入
//引入vuex
import store from './store'
new Vue({el: '#app',router,store,components: { App },template: '<App/>',data:function(){return{wbWinList: [] // 定义的变量,全局参数}},
})
2、index.js
import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/user'Vue.use(Vuex);const store = new Vuex.Store({state: {// 定义要传递的数据datas: [],id:1},getters: {doneTodos (state) {state.datas.push({"dade":666})return state.datas.length+8}},// 定义修改数据的 mutationmutations: {setData(state, newDatas) {state.id = newDatas;}},// 定义分发数据的 action,用于异步调用mutationsactions: {updateDatas({ commit }, datas) {commit('setData', datas);}},// 模块化modules:{user}
});// 全局使用
// console.log(this.$store.state)
// console.log(this.$store.state.user.id)export default store;
2、user.js
import Vue from 'vue';
import Vuex from 'vuex';Vue.use(Vuex);const user = new Vuex.Store({state: {// 定义要传递的数据id:2},mutations: {// 定义修改数据的 mutationSET_DATAS(state, newDatas) {state.datas = newDatas;}},actions: {// 定义分发数据的 actionupdateDatas({ commit }, datas) {commit('SET_DATAS', datas);}}
});export default user;
3、使用
<template><div @click="dadepp">{{dades}}</div>
</template><script>export default{data(){return {dades:6666}},methods:{dadepp(){// 调用gettersconsole.log(this.$store.getters.doneTodos)console.log(this.$store.state)console.log(this.$store.state.user.id)// 调用mutationsthis.$store.commit("setData",10)console.log(this.$store.state)//调用actionsthis.$store.dispatch("updateDatas",20)console.log(this.$store.state)}}}
</script><style scoped>.dade{-webkit-box-shadow: 0 2px 0px 0 rgba(0,0,0,.1);box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);}.draggable-div {position: absolute;}
</style>