Vuex(分模块组织项目结构)
一、初始化项目并安装Vuex依赖
1、初始化一个项目vuex-demo
- 运行vue init webpack-simple vuex-demo
- 运行cd vuex-demo
- 运行cnpm install
2、安装vuex
运行cnpm install vuex -S (安装vuex生产依赖)
3、新建的项目的初始结构
二、分模块组织项目结构
- |-src
- |-store
- |-index.js
- |-getters.js
- |-actions.js
- |-mutations.js
- |-mutation-types.js(定义常量,非必须)
- |-modules //分为多个模块,每个模块都可以拥有自己的state、getters、actions、mutations
- |-user.js
- |-cart.js
- |-goods.js
- | ....
创建对应的store结构后,vuex-demo2项目结构为:
2.1 写App.vue中的代码
1 <template> 2 <div id="app"> 3 <h1>{{ msg }}</h1> 4 <!-- 写点击事件 --> 5 <button @click="increment">增加</button> 6 <button @click="decrement">减少</button> 7 <button @click="incrementAsync">异步增加</button> 8 <!-- 4.页面上显示store对象 --> 9 <p>当前数字为:{{count}}</p> 10 <p>{{isEvnOrOdd}}</p> 11 </div> 12 </template> 13 14 <script> 15 //导入辅助函数 16 import {mapGetters,mapActions} from 'vuex' //导入辅助函数 17 export default { 18 name: 'app', 19 data () { 20 return { 21 msg: '欢迎来到Vuex' 22 } 23 }, 24 //调用辅助函数mapGetters 25 computed:mapGetters([ 26 'count', 27 'isEvnOrOdd' 28 ]), 29 //调用辅助函数mapActions 30 methods:mapActions([ 31 'increment', 32 'decrement', 33 'incrementAsync' 34 ]) 35 } 36 </script>
2.2 写mudules/user.js中的代码
1 import types from '../mutation-types.js' 2 3 //定义state 4 var state = { 5 count:6 6 } 7 //定义Getters 8 var getters={ 9 count(state){ 10 return state.count; 11 } 12 } 13 //定义Actions 14 const actions={ 15 increment({commit,state}){ 16 commit('types.INCREMENT'); 17 }, 18 decrement({commit,state}){ 19 if(state.count>10){ 20 commit('types.DECREMENT'); 21 } 22 } 23 } 24 //定义mutations 25 const mutations={ 26 [types.INCREMENT](state){ 27 state.count++; 28 }, 29 [types.DECREMENT](state){ 30 state.count--; 31 }, 32 } 33 34 export default { 35 state, 36 getters, 37 actions, 38 mutations 39 }
2.3写mutation-types.js中的代码
1 //定义类型常量 2 const INCREMENT = 'INCREMENT' 3 const DECREMENT = 'DECREMENT' 4 5 export default { 6 INCREMENT, 7 DECREMENT 8 }
2.3 写getters.js中的代码
1 //定义方法 2 var getters={ 3 isEvnOrOdd(state){ 4 return state.user.count%2==0?'偶数':'奇数'; 5 } 6 } 7 8 export default getters;
2.4 写actions.js中的代码
1 const actions={ 2 incrementAsync({commit,state}){ 3 //异步操作 4 var p=new Promise((resolve,reject)=>{ 5 setTimeout(()=>{ 6 resolve(); 7 },3000); 8 }); 9 p.then(()=>{ 10 commit('increment'); 11 }).catch(err=>{ 12 console.log('异步操作'); 13 }) 14 } 15 } 16 17 export default actions;
2.5 写index.js中的代码
1 import Vue from 'vue' 2 import Vuex from 'vuex' 3 4 Vue.use(Vuex); 5 6 import getters from './getters.js' 7 import actions from './actions.js' 8 import user from './modules/user.js' 9 10 export default new Vuex.store({ 11 getters, 12 actions, 13 modules:{ 14 user 15 } 16 })