Vue.js數(shù)據(jù)狀態(tài)管理-Vuex

上次分享回顧

父子組件的通信

  • 父 -> 子: props
  • 子 -> 父: 自定義event
  • 組件文檔化

Vuex起步

Vuex主要應(yīng)用于中、大型單頁應(yīng)用的數(shù)據(jù)狀態(tài)管理架構(gòu)。

為什么要數(shù)據(jù)狀態(tài)管理?

  • 組件數(shù)據(jù)共享

組件之間如何數(shù)據(jù)共享(組件通信)

  • 父 -> 子:props
  • 子 -> 父:自定義event
  • 兄弟之間?其他非父子? :自定義event?

可能的解法

  1. 自定義event

    var bus = new Vue()
    // in component A's method
    bus.$emit('id-selected', 1)
    
    // in component B's created hook
    
    bus.$on('id-selected', function(id){
      //...
    })
    
  2. 共享數(shù)據(jù)源

    const srcData = {
      count: 0
    }
    
    const vmA = new Vue({
      data: srcData
    })
    
    const vmB = new Vue({
      data: srcData
    })
    

存在的問題

  • 誰在emit事件?誰在on事件?父組件和子組件強(qiáng)耦合
  • 如何追蹤數(shù)據(jù)的狀態(tài)變化?
  • 業(yè)務(wù)邏輯遍布各個(gè)組件,導(dǎo)致各種意想不到的問題

Vuex基本概念

  • state
    • 狀態(tài)的容器
  • getters
    • 狀態(tài)的獲取函數(shù)
  • mutations
    • 修改狀態(tài)的事件回調(diào)函數(shù)
  • actions
    • 分發(fā)修改狀態(tài)的事件
const store = new Vuex.Store({
  //state
  state: {
    count: 0
  },
  //mutations
  mutations: {
    INIT (state, data) {
      state.count = data.count
    },
    INCREASE (state) {
      state.count++
    },
    DECREASE (state) {
      state.count--
    }
  },
  //getters
  getters: {
    getCount (state) {
      return state.count
    }
  },
  //actions
  actions: {
    init(context){
      context.commit('INIT', {
        count: 10
      })
    },
    inc(context){
      context.commit('INCREASE')
    },
    dec(context){
      context.commit('DECREASE')
    }
  }
})

Vuex基本理解

  • 數(shù)據(jù)的集合其中處理(DB)
  • 數(shù)據(jù)的操作集中處理 (CRUD)
  • 所有對(duì)數(shù)據(jù)的操作(CRUD)以請(qǐng)求(commit)的方式提交處理 (DAO)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容