第七課時: 狀態管理, Vuex進階

1.插件
因爲vuex是存在內存中的,所以刷新頁面的時候其中的值就會初始化。爲了刷新時不讓其改變,可以開發一個插件,把state狀態都存在本地中。

saveInLocal.js:

    export default store => {
      if (localStorage.state) store.replaceState(JSON.parse(localStorage.state))
      store.subscribe((mutation, state) => {
        localStorage.state = JSON.stringify(state)
      })
    }

在store文件夾中的index.js 添加代碼:

import saveInLocal from './plugin/saveInLocal'
Vue.use(Vuex)

export default new Vuex.Store({
    //...
    plugins: [ saveInLocal ]
})

2.嚴格模式
開啓嚴格模式,僅需在創建 store 的時候傳入 strict: true:

const store = new Vuex.Store({
  // ...
  strict: true
})

在嚴格模式下,無論何時發生了狀態變更且不是由 mutation 函數引起的,將會拋出錯誤。這能保證所有的狀態變更都能被調試工具跟蹤到。

3.vuex + 雙向綁定
必須承認,這樣做比簡單地使用“v-model + 局部狀態”要囉嗦得多,並且也損失了一些 v-model 中很有用的特性。另一個方法是使用帶有 setter 的雙向綁定計算屬性:

<input v-model="message">

// ...
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章