首先在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"])
},
同时也可以和属性引入一样,前面起别名,以上。如果本文对你有帮助,欢迎点赞,或留言评论。