vuex_vuex的模块化

store目录

|-- store
|   |-- actions.js
|   |-- getters.js
|   |-- index.js
|   |-- mutations.js
|   |-- state.js
|   |-- module
|       |-- article.js
|       |-- index.js
|       |-- owner.js
|       |-- user.js

根文件store/index.js

import { createStore } from 'vuex'
import state from '@/store/state'
import mutations from '@/store/mutations'
import actions from '@/store/actions'
import getters from '@/store/getters'
import index from '@/store/module/index' // 首页数据模块
import owner from '@/store/module/owner' // 博客主人数据模块
import user from '@/store/module/user' // 访问者数据模块
import article from '@/store/module/article' // 文章数据模块 
const store = createStore({
  state: () => state,
  mutations,
  actions,
  getters,
  modules: {
    index, owner, user, article
  }
})

export default store

模块组件, 以owner.js为例

/* 用户相关的数据 */
import { reqGetUserDataByHtml } from '@/ajax/api'
import { handleUserData } from '@/util'
export default {
  namespaced: true,
  state: () => ({
    userData: {
      name: '', 
      homePageHref: '', 
      ageStr: '', 
      fansCount: 0, 
      fansHref: '', 
      followCount: 0, 
      followHref: '', 
      avator: '',
    },
  }),
  mutations: {
    updateUserData (state, payload) {
      state.userData = payload
    },
  },
  actions: {
    async getUserDataByHtml ({ commit, state }) {
      try {
        const result = await reqGetUserDataByHtml()
        commit('updateUserData', handleUserData(result))
        return { code: 1 }
      } catch (err) {
        return { code: 0, msg: '解析用户数据出现错误' }
      }
    },
  },
  getters: {}
}

在组件中的使用

  • 使用模块的state数据
// $store.state.[模块名][变量名]
$store.state.article.curArticleData
  • 调用模块的mutations方法
// $store.commit('[模块名]/[函数名]', 数据)
$store.commit('article/updateCurArticleData', { id })
  • 调用模块的actions方法
// $store.dispatch('[模块名]/[函数名]')
$store.dispatch('index/getEssayDataByPage')
posted @ 2023-10-02 00:39  Syinho  阅读(11)  评论(0编辑  收藏  举报