Vuex分模块开发

首先在src目录下新建文件夹store

在store文件夹下 新建一个model文件夹用来管理vuex模块文件,新建一个index.js用来合并模块,一起导出

结构如下

 

打开lable.js,编写模块代码,代码格式如下

const state= {}
const getters={}
const mutations={}
const actions={}
const modelUser={
state:state,
getters:getters,
mutations:mutations,
actions:actions
}
export default modelUser

 我的实例代码如下

const state = { HotTags: "", }
const getters = {
    HotTags: state => {
        return state.HotTags
    }
}
const mutations = {
    getHotTags(state) {
        fetch("/api/mybatis")
            .then(response => response.json())
            .then(json => {
                state.HotTags = json
                console.log("VUEx")
            })
    }
}
const actions = {
    getHotTags({ commit }) {
        setTimeout(() => {
            commit('getHotTags')
        }, 0)
    }
}
const modellable = {
    state: state,
    getters: getters,
    mutations: mutations,
    actions: actions
}
export default modellable

打开index.js文件

引入模块 

import modulelable from './model/lable'

引入vue和vuex

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

 编写导出代码,格式如下

const store = new Vuex.Store({
    modules: {
        modulelable: Object.assign({}, {          //lable 用户store
            namespaced: true,
        }, modulelable),
    }
})
export default store

打开main.js,引入store 代码块,添加到vue实例中,完成

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

使用方法

1.直接使用

this.$store.state.modulelable.name

在属性前面加入模块名

2.引入mapState 函数

import { mapState } from 'vuex'
   computed: {
        ...mapState({
            userName: state => state.modulelable.name //modeuleUser
        })
    },

使用vuex方法

import { mapGetters } from "vuex";

引入函数

 computed: {
        ...mapGetters("modulelable",["HotTags"])
    },

 同时也可以和属性引入一样,前面起别名,以上。如果本文对你有帮助,欢迎点赞,或留言评论。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值