Vuex is built in uni-app, we only need to reference it.
First, create a store directory in the root directory and create index.js in it;
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
hasLogin: false,
userInfo: {
}
},
mutations: {
login(state, provider) {
state.hasLogin = true;
state.userInfo = provider;
uni.setStorage({
//缓存用户登陆状态
key: 'userInfo',
data: provider
})
},
logout(state) {
state.hasLogin = false;
state.userInfo = {
};
uni.removeStorage({
key: 'userInfo'
})
}
},
actions: {
}
})
export default store
Then reference the mount in main.js
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
Vue.prototype.$store = store
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount()
Use in the page
Introduce in script
import {
mapState,mapMutations} from 'vuex';
Then mapState must be written in computed
<view>{
{
position}}</view>//使用vuex中的值
export default {
data() {
return {
address: "",
}
},
computed: mapState(['position', 'userData'])
}
mapMutations is written in methods
methods: {
...mapMutations(['getPosition', 'getUserData'])
},
//使用的话直接调用this.getPosition就可以了