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;
}
}
})
(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')
今天看了在知乎上看了一篇文章,《学霸的努力程度到底可以有多可怕?》可以搜索看看,当年高中没好好学习,真的后悔