vue中学习使用Vuex详解
在SPA单页面组件的开发中 Vue的vuex和React的Redux 都统称为同一状态管理,个人的理解是全局状态管理更合适;简单的理解就是你在state中定义了一个数据之后,你可以在所在项目中的任何一个组件里进行获取、进行修改,并且你的修改可以得到全局的响应变更。下面咱们一步一步地剖析下vuex的使用:
首先要安装、使用 vuex
首先在 vue 2.0+ 你的vue-cli项目中安装 vuex :
npm install vuex
vuex的执行流程如下:

1.在Vue项目中,新建store文件夹,内容如下:

2.store/index.js,内容如下:
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state,
actions,
mutations
})
3.store/state.js,内容如下:
export default {
homeList:{},
}
4.store/action.js,内容如下:
import { getHomeCasual } from './../api/index'
import { HOME_LIST } from './mutation-types';
export default {
async getHomeListData({commit}){
const result = await getHomeCasual();
commit(HOME_LIST,{homeList:result});
}
}
5.store/mutation-types.js,内容如下:
export const HOME_LIST = 'home_list'
6.store/mustations.js,内容如下:
import { HOME_LIST } from './mutation-type'
export default {
[HOME_LIST](state,{homeList}){
state.homeList = homeList;
}
}
main.js中引入store文件
import store form './store/index'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
组件中调用:
import { mapState } from 'vuex'
computed:{
...mapState(['homeList'])
},
mounted(){
this.$store.dispatch(['getHomeLiseData'])
},
watch:{
homeList(){
this.$nextTick(()=>{
//深度监听数据变化,进行相应的初始化项目
})
}
}

浙公网安备 33010602011771号