uni-app store 状态管理学习,多写几遍就会了

uni-app使用了一段时间了,一直没有用到store 状态管理,还是应该学习一下,以后会用到的

1.使用hbuiderx创建uni-app项目

2.与static同级创建store文件夹,store文件夹下创建index.js
在这里插入图片描述

3.关键index.js

//(1) 引入Vue 和 Vuex 
import Vue from 'vue'
import Vuex from 'vuex'
//(2) 使用Vuex
Vue.use(Vuex)
//(3) 创建store 对象 

	const store = new Vuex.Store({
		//state中是需要管理的全局变量
		state:{
				userName:'',
				hasLogin:false
		},
		//mutations 是操作state中变量的方法
		mutations:{
			login(state,name){  //登录成功修改 全局变量
				state.userName= name;
				state.hasLogin= true;
			},
			loginOut(state){     //退出登录修改 全局变量
				state.userName= '';
				state.hasLogin= false;
			}
		}

	})
	export default store

在这里插入图片描述

(4) 导出store

export default store

4.这样简单的store模块就写完了,接下来是引用

首先在main.js中注册Vuex

import store from './store'
Vue.prototype.$store = store
const app = new Vue({
	store,
    ...App
})

在这里插入图片描述

5.在页面中使用 login.vue页面中使用,要使用store首先在页面script中引用

import {mapState,mapMutations} from 'vuex'

与vue的data同级的computed 生命周期中使用注册变量

computed:{
	...mapState(['userName','hasLogin'])
}

页面渲染直接{{userName}}或者this.hasLogin使用变量

然后methods中

methods:{
	...mapMutations(['login','loginOut']),
}

使用方法直接
this.login()
6.store 状态初始化 store 下的 index.js中

1.state

state:{
	num:0
}

2.actions

actions:{
		init(){
			this.commit('initNum',100)
		}

}

3.mutations

mutations:{

	initNum(state,num){
		state.num = num
	
	}
}

4.在页面中调用actions的init方法

this.$store.dispatch('init')

今天看了在知乎上看了一篇文章,《学霸的努力程度到底可以有多可怕?》可以搜索看看,当年高中没好好学习,真的后悔

  • 9
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端喜欢研究技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值