vuex的用法及介紹

使用:

主要使用場景是適合大型單頁面

  • 倉庫store包含了應用的數據(狀態)和操作過程,任何組件使用同一store的數據,只要store的數據變化,對應的組件也會立即更新
  • 數據保存在Vuex的state字段內,任何頁面組件都可以通過$store.state.變量名稱去讀取數據
  • 修改state數據,顯示地提交mutations,使用this.$store.commit方法來執行mutations,例如,mutations裏面的方法可以設置第二個參數,第二個參數可以設置默認值,也可以傳入參數
  • “getter”(可以認爲是 store 的計算屬性)。就像計算屬性一樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被重新計算,有時候某個數據是計算之後獲取的數據,用getter減少代碼冗餘
  • Action 提交的是 mutation,而不是直接變更狀態。
  • Action 可以包含任意異步操作。
  • Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用 context.commit 提交一個 mutation,或者通過 context.state 和 context.getters 來獲取 state 和 getters

具體操作實例可以看如下代碼

  • 使用vuex需要先在main.js中引入,具體可看我的另一篇關於main.js設置的博文

https://blog.csdn.net/weixin_44258964/article/details/105835057

vuex的配置

//vuex/store.js文件
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  name: 'yan',
  age: 23,
  obj: [{ bookname: '荒誕', num: 20 }, { bookname: '行爲學', num: 30 }, { bookname: '荒誕行爲學', num: 40 }]
}
const mutations = {
  changename (state, name) {
    state.name = name
  },
  changeage (state) {
    state.age++
  }
}
//需要統一設置的變量可在此設置
const getters = {
  checkObj (state) {
    return state.obj.filter(res => { return res.num > 25 })
  }
}
// 異步不是很理解如何運用
const actions = {
  changeage (context) {
    context.commit('changeage')
  }
}

const store = new Vuex.Store({
  //  vuex的配置
  state, mutations, getters, actions
})

export default store

vuex的應用

//使用文件
changName () {
      // vuex通過commit提交修改
      this.$store.commit('changename', 'yanjiazhen')
      this.$store.commit('changeage')
      // getter獲取計算內容
      this.obj = this.$store.getters.checkObj
}

缺點:

  • 頁面刷新會導致數據丟失

錯誤解決

控制檯報錯TypeError: WEBPACK_IMPORTED_MODULE_1_vuex.a.store is not a constructor
TypeError: “x” is not a constructor
解決:創建Vuex實例的時候,Store需要大寫 new Vuex.Store

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章