您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何在uni-app使用vuex

2024/5/4 2:01:58发布24次查看
方法: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和vueximport 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的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product