如何在uni-app使用vuex
时间:2022-02-23 17:50
方法:1、项目根目录下新建store目录,该目录里创建“index.js”文件;2、“index.js”下引入vue和vuex;3、“main.js”中挂载Vuex;4、在“pages/index/index.vue”中使用vuex即可。
本教程操作环境:windows7系统、vue2.9.6&&uni-app2.5.1版,DELL G3电脑。
uni-app中使用vuex的方法:
在uni-app中内置了vuex,我们只需要引用就行了
1、在 uni-app 项目根目录下新建 store 目录,在 store 目录下创建 index.js
2、新建的index.js下引入vue和vuex,具体如下:
- //引入vue和vuex
- import Vue from 'vue'
- import Vuex from 'vuex'
- Vue.use(Vuex)
- const store = new Vuex.Store({//全局变量定义
- state: {
- forcedLogin: false,//是否需要强制登录
- hasLogin: false,
- userName: "",
- userId:'',
- token:'',
- pointId:'',
- },
- mutations: {
- login(state, user) {
- state.userName = user.username || '';
- state.hasLogin = true;
- state.userId = user.id || '';
- state.token = user.token || '';
- state.pointId = user.pointId || '';
- },
- logout(state) {
- state.userName = "";
- state.hasLogin = false;
- state.userId = '';
- state.token = '';
- state.pointId = '';
- }
- }
- })
- export default store
3、需要在 main.js 挂载 Vuex
- import store from './store'
- Vue.prototype.$store = store
想要定义的这个 js 文件中的变量和方法能在各个页面使用并生效,需要先在项目目录下的 main.js 文件中导入这个 js 文件并声明方法,如下图所示:
4、在 pages/index/index.vue 使用
先在页面导入vuex的方法
然后,在 computed 计算属性方法中使用 mapState 对全局变量进行监控。
一进来index.vue 页面,在onload()页面加载的时候,判断是否已是登陆状态,不是的话,弹出对话框,提示进行‘登陆操作’
登陆页面
先在页面导入vuex的方法,如下:
在 computed 计算属性方法中使用 mapState 对全局变量进行监控,在 method中使用 mapMutations 进行全局方法监控,如下所示:
网络请求成功后,在回调函数 success 中调用该方法,并把回调函数的返回值数据传给 login 方法
随后 store/ index.js 文件中的login方法会把传过来的用户数据保存在vuex。
扩展
在vue文件中使用 取值,比如其中的token,可以使用‘this.$store.state.token’这样来取。
在js文件中使用
1、import store from '../../store' 先引用
2、store.state.token 取值
更多编程相关知识,请访问:编程视频!!
以上就是如何在uni-app使用vuex的详细内容,更多请关注gxlsystem.com其它相关文章!