uni使用store模块化(个人笔记)

348 阅读1分钟

1.目录结构 index.js主文件,module其他模块文件

image.png

2.index.js

import Vue from "vue"
import Vuex from "vuex"
import loginStore from "./module/loginStore.js"
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		//公共的变量,这里的变量不能随便修改,只能通过触发mutations的方法才能改变
		name: '阿毛子'
	},
	mutations: {
		//相当于同步的操作
	},
	actions: {
		//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变
	},
	modules: { //放入其他模块的store
		loginStore
	}
})
export default store

3.module的js文件

const LoginStore = {
	namespaced: true, //命名空间
	state: {
		//公共的变量,这里的变量不能随便修改,只能通过触发mutations的方法才能改变
		name: '登录的store'
	},
	mutations: {
		//相当于同步的操作
                setName(state, data){
                state.name=data
                }
	},
	actions: {
		//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变
		async getName(data){
                //这里调用接口 
                //通过
                commit('setName',data)
		}
	}
}
export default LoginStore

4.main.ts挂载

import store from "@/store/index.js"
Vue.prototype.$store = store
const app = new Vue({
	store,
    ...App
})

5.页面使用

 onLoad() {
        console.log(this.$store);
        //调用方法
        this.$store.dispatch('loginStore/getName', '张三');
    },

6.效果

image.png