一、vuex与全局变量globalData的区别
uni-app像小程序一样有globalData,是简单的全局变量,如果使用状态管理,请使用vuex 一些简单的常量或变量,请使用globalData。涉及到响应式的数据和跨组件共享数据、跨页面共享数据,建议使用vuex
二、uniapp vuex使用
目录结构如下
1. 根目录创建vue x目录,创建index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import cart from './modules/cart.js'
import users from './modules/users.js'
export default new Vuex.Store({
state: {
token: ''
},
getters: {
hasLogin(state) {
return !!state.token
}
},
mutations: {
setToken(state, data) {
const { token, userInfo, uid, userID, userSig } = data
state.isLogin = true
state.token = token
state.userInfo = userInfo
state.myUserID = userID
uni.setStorageSync("token", token);
uni.setStorageSync("userInfo", userInfo);
uni.setStorageSync('userID', userID)
uni.setStorageSync('userSig', userSig)
},
},
actions: {
getUserInfo({commit},data) {
commit('setToken', data)
},
},
modules: {
cart,
users,
}
})
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
2. 模块化代码
export default {
state: {
position: ''
},
getters: {},
mutations: {
setPositon(state, data) {
state.position = data
}
},
actions: {
async updateUserPositon({ commit }, data, rootState) {
uni.getLocation({
type: "wgs84",
success: (res) => {
let getAddressUrl =
"https://apis.map.qq.com/ws/geocoder/v1/?location=" + res.latitude + "," + res.longitude + "&key=xxx";
uni.request({
url: getAddressUrl,
success: (res) => {
if (res.statusCode == 200) {
if (res.data && res.data.status == 0) {
const position = res.data.result.address_component.city;
commit('setPositon', position)
}
}
},
});
},
fail: (err) => {
console.log(err)
},
});
}
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
3. 在 main.js 中导入store文件
import App from './App'
import Vue from 'vue'
import store from './vuex/index.js'
Vue.prototype.$store = store
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount()
4. 调用
// 获取state中的值
this.$store.state.token
// 获取模块中state的值
this.$store.state.users.position
// 修改state中的值
this.$store.commit('setPositon', data);
// 调用actions中的方法
this.$store.dispatch('updateUserPositon',data)
import { mapState, mapMutations, mapActions} from 'vuex'
computed: {
...mapState({
position: state => state.users.position
})
}
methods: {
...mapMutations(['setPositon']),
...mapActions(['updateUserPositon'])
}