uniapp vue3 使用vuex
uniapp 内置了vuex 所以不用安装
1 根目录下 创建store/index.js
import {createStore} from 'vuex'//导入createStore构造函数 export default createStore({ state:{ //Vuex的状态,实际上就是存数据的地方 person:{ name:'51zuso', age:6 } }, getters:{ //提供获取Vux状态的方式, 注意在组件中调用时getPerson是以属性的方式被访问 getPerson(state){ return state.person } }, mutations:{ //提供直接操作Vuex的方法,注意mutations里的方法中不能有任何异步操做 ageGrow(state, value){ //第一个参数state为Vuex状态;第二个参数为commit函数传来的值 state.person.age += value } }, actions:{ //提供通过mutations方法来简介操作Vuex的方法 ageGrow(context, value){ //第一个参数context为上下文,提供一些方法;第二个参数为dispatch函数传来的值 context.commit('ageGrow', value) } }, })
2 main.js引入store
import store from '@/store'; //引入vuex app.use(store) //使用vuex
3 页面中引用
import {useStore} from 'vuex'; const store = useStore();//获取store对象 let person = store.getters.getPerson; //获取数据 store.commit('ageGrow',10); //使用方法修改数据