nuxt的状态化存储

558 阅读2分钟

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战

nuxt的状态化存储

nuxt框架本身就内置了Vuex,不需要再额外引入。但如果项目中要启用状态树来管理状态,需要自己去新建store目录。

新建store目录后,Nuxt.js会自动再项目中引入vuex模块,将之加到vendors构建配置中去,并且设置Vue根示例的store配置项。

模块方式

src目录中新建store目录,store目录下再新建.js文件,每个文件对应一个模块。默认index是根模块,nuxt也支持具名模块(自定义命名)。

具名模块在引用时,需要带上文件名,如下图: store-nuxt.png

模块文件注意事项

  1. 模块文件,state值应该为functionmutations用于定义同步方法,提交修改state状态值;actions用于定义异步方法,官方建议不直接修改state值,而是通过commit调用mutations修改state状态值;写法如下:
    export const state = () => ({
            dict: Cookies.get('dict') || {}
    })
    export const mutations = {
            SET_DICTINFO: (state, data) => {
                    state.dict = data;
                    Cookies.set('dict', data, { expires: 30 })
            }

    }
    export const actions = {
            // 获取数据字典
            getSysDict({ commit, state }) {
              return new Promise((resolve, reject) => {
                getDict().then(response => {
                  commit("SET_DICTINFO", response)
                  resolve(response)
                }).catch(error => {
                  reject(error)
                })
              })
            }
    }
  1. 模块文件中的stateactionmutationgetters可分开文件存放,也可以放同个文件中。如上图,getters文件分开存放,getters文件写法如下:
const getters = {
  // 指向根模块下的状态
  device: state => state.device,
  userInfo: state => state.userInfo,
  // 指向具名模块下的状态
  remark: state => state.upload.remark,
  purchaseUrl: state => state.upload.purchaseUrl,
  fileType: state => state.upload.fileType
}
export default getters

页面中使用store模块方法

  1. page中引用vuexmethods中通过this.$store.dispatch调用actions异步方法,通过this.$store.commit调用mutations同步方法,通过this.$store.state拿到状态值,如下: page中调用根模块下的actions方法:
    logout() {
      this.$store.dispatch('logout').then(res => {
        setTimeout(()=>{
          this.$router.push('/')
          this.$forceUpdate();
        })
      }).catch(err => {

      })
    },

page中调用具名文件下的mutations方法:

    this.$store.commit('upload/SET_WEBKIT_DIRECTORY', false)
  1. 通过辅助函数 mapGettersmapStatemapMutationsmapActions mapGetters 相当于计算属性,通过对state进行处理转换,返回需要的值,在page中的写法如下:
    computed: {
      ...mapGetters(['userInfo']), 
    },

mapState,用法与mapGetters差不多,但它只是state的简单映射

    computed: {
      ...mapState(['userInfo']), 
    },

mapMutationsmapActions的用法同上面差不多

    methods: {
      ...mapMutations(['SET_OPENSTAFF']),
      askForDeploy() {
        this.SET_OPENSTAFF(true)
      }
    }
  }

注意事项

  1. store下的模块不能跨文件修改其它模块中的state
  2. 若项目中有设置状态树,nuxt.js在服务端初始化时(nuxtServerInit),Vuex被调用并且可预填存储vuex,这里涉及到nuxt的生命周期,具体的查看下一篇文章~