vuex使用模块化开发

文件 store.js

import Vue from 'vue'
import Vuex from 'vuex'

import ager from './modules/ager'
import parStore from '@/pages/par/store'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    ager,
    parStore,
  },
})

文件 modules/ager.js

const ager = {
  namespaced: true,
  state: {
    id: 1
  },
  getters: {
  },
  // 处理同步函数 修改state中数据
  mutations: {
     addTab (state, tab) {
      state.tabs.push(tab)
    },
  },
//处理异步函数 
  actions: {
    addTabAsync ({ state, commit }, tab) {
      let targetTab = tab
      const currTime = new Date().getTime()
      const tabId = targetTab.id
      const index1 = state.tabs.findIndex(item => {
        return item.id === tabId
      })
      if (index1 === -1) {
        targetTab.time = currTime
        commit('addTab', targetTab)
      } else {
        state.tabs[index1].time = currTime
        commit('setTab', index1, state.tabs[index1])
      }
      commit('setCurrentId', tabId)
      return targetTab
    }
}
export default ager



文件@/pages/par/store

const state = {
  id: 1
}

const getters = {}

const mutations = {
  addTab (state, tab) {
      state.tabs.push(tab)
    },
}

const actions = {
   addTabAsync ({ state, commit }, tab) {
      let targetTab = tab
      const currTime = new Date().getTime()
      const tabId = targetTab.id
      const index1 = state.tabs.findIndex(item => {
        return item.id === tabId
      })
      if (index1 === -1) {
        targetTab.time = currTime
        commit('addTab', targetTab)
      } else {
        state.tabs[index1].time = currTime
        commit('setTab', index1, state.tabs[index1])
      }
      commit('setCurrentId', tabId)
      return targetTab
    }
  },
}

const parStore = {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
}

export default parStore

就可以在跟组件 Main.js 引入 import store from ‘store/store.js‘,并将vuex挂载到 vue实例上 。那么在跟组件下的子组件 就可以用vuex来使用store.js中的函数,但是有不同地方的是,在子组件中引入方式不同。
import { createNamespacedHelpers } from ‘vuex’
const { mapState , mapActions } = createNamespacedHelpers(‘ager’,‘parStore’)

computed: {
// 通过vuex来拿到id
…mapState({‘id’})
或者
…mapState({ panes: state => state.id }, { currentId: state => state.id})
}
methods: {
// 从vuex 引入异步函数 addTabAsync
…mapActions([‘addTabAsync’]),
}
在 组件中 可以 直接 this.addTabAsync 来对函数进行调用 在页面中 用到 state中的数据 可以 {{id}} 或者属性绑定 :value=‘id’ 代替v-model=‘id’

发布了24 篇原创文章 · 获赞 2 · 访问量 9181

猜你喜欢

转载自blog.csdn.net/sunmeng_sunmeng/article/details/103668042