vue前台(二)vuex的模块化

放图

 

 

home模块的vuex   home.js

// 引入ajax的函数
import {reqCategoryList} from '@/api'

const state= {
  CategoryList:[]
}

const mutations={
  RECEIVECATEGORYLIST(state,data){
    state.CategoryList=data
  }
}

const actions={
  // 发送ajax请求
  // getCategoryList({commit}){
  //   reqCategoryList().then(res=>{
  //     commit('RECEIVECATEGORYLIST',res.data)
  //   })
  // }

  async getCategoryList({commit}){
    const result= await reqCategoryList()
    if(result.code===200){
      commit('RECEIVECATEGORYLIST',result.data)
    }
    
  }


  
}

const getters={}

//暴露store
export default {
  state,
  mutations,
  actions,
  getters
}

 

总的vuex   index.js

// 引入vue
import Vue from 'vue'
//引入vuex插件
import Vuex from 'vuex'

// 引入组件的store
import home from './home'
//申明插件
Vue.use(Vuex)

const state={}

const mutations={}

const actions={}

const getters={}

//暴露store
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
    modules:{
      home
    }
})

 

然后入口文件main.js中注册

// 引入vuex
import store from '@/store'
 
new Vue({
 
  render: h => h(App),
  // 注册路由
  router,
  store
}).$mount('#app')

 

在typenav组件中dispatch到vuex

  mounted(){
        getcategoryList()
    },

    methods:{
        //dispatch到vuex
        getcategoryList(){
            this.$store.dispatch('getCategoryList')
        }
    }

 

然后从vuex中获取数据
 computed:{


    // categoryList(){
    //   return this.$store.state.categoryList
    // }

    // ...mapState(['categoryList'])
    // ...mapState({categoryList:"categoryList"})

    //上面两种写法是一回事,mapState映射的时候默认映射的就是总的store的state内部的数据
    //如果使用了vuex模块化开发,那么数组的形式就无法使用了

    // categoryList(){
    //   return this.$store.state.home.categoryList
    // }
    
    ...mapState({
      categoryList : state => state.home.categoryList
    })


  }

填充模板数据

 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

posted @ 2020-07-16 10:07  全情海洋  阅读(599)  评论(0编辑  收藏  举报