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(()=>{
            //深度監聽數據變化,進行相應的初始化項目
        })
    }
}
        

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM