uni-app使用vuex对项目的组建状态进行管理非常方便,也可以进行全局变量使用。
如果不了解什莫是vuex的朋友大家可以先去官网看看。
在 uni-app 项目根目录下新建 store 目录,在 store 目录下创建 index.js 定义状态值。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)”
const store = new Vuex.Store({state: {login: false,token: '',avatarUrl: '',userName: ''},mutations: {login(state, provider) {console.log(state)console.log(provider)state.login = true;state.token = provider.token;state.userName = provider.userName;state.avatarUrl = provider.avatarUrl;},logout(state) {state.login = false;state.token = '';state.userName = '';state.avatarUrl = '';}}
})
export default store
然后,需要在 main.js 挂载 Vuex
import store from './store'
Vue.prototype.$store = store
最后,在 pages/index/index.vue 使用
<script>import {mapState,mapMutations} from 'vuex';export default {computed: {...mapState(['avatarUrl', 'login', 'userName'])},methods: {...mapMutations(['logout'])}}
</script>
在其他页面使用的时候用 取值,比如其中的token,可以使用用‘this.$store.state.token’这样来取。
我在此项目中有个地方使用了vuex,就是购买时,会弹出购买规格,人数,营期。然后需要将营期id和价格,人数传值到确认订单页面进行付款。
先引入import store from '../../../../store/index.js'
let cart=[信息];
然后提交
this.$store.commit("addCart",cart);
在store的index.js的mutations中添加方法
addCart(state,data){state.cart = data;
}
然后在确认订单页面获取cart的值,this.cart=this.$store.state.cart;
这样就可以使用了。