Uni-App中使用vuex
vuex是管理程序共享状态的仓库。比如存储用户登录状态,又比如很多页面都需要的数据。vuex中通常有state,getters, actions, mutations这几个对象。
创建vuex
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import system from './system.js'
Vue.use(Vuex)
export default new Vuex.Store({
//模块化处理
modules: {
system,
}
})
// store/system.js
//存放数据。相当于vue页面中的data对象
const state = {
info:'测试数据' ,
}
//计算属性。 类似vue页面中的computed
const getters = {
getinfo: function(state){
return state.info,
}
}
//存放方法,mutations中的方法必须是同步函数。
const mutations = {
getSystem(state){
console.log('mutations','mutations测试')
},
mutdata(state,pars){
console.log('pars',pars)
}
}
//用来提交mutations,而不是直接变更状态。actions可以处理异步函数
const actions = {
setmut({ commit }){
//提交mutdata函数
commit('mutdata','更新数据')
}
}
export default {
state,
getters,
mutations,
actions,
}
system.js是我们自己创建的文件。我们还可以创建其他模块,创建完之后需要在store/index.js中加载
挂载vuex
//main.js
import Vue from 'vue'
import App from './App'
import store from 'store/index.js' //引用vuex
...
Vue.prototype.$store = store //挂在到全局属性
App.mpType = 'app'
const app = new Vue({
...App,
store //传入Vue中
})
app.$mount()
调用vue
在vue文件中的调用方法
方法一、直接调用
// pages/index.vue
onLoad() {
//state的调用
console.log('store', this.$store.state.system.info)
//getters的调用
console.log('getters', this.$store.getters.getinfo)
//mutations通过store中的commit方法调用
this.$store.commit('getSystem') // mutations mutations测试
//传递参数。
this.$store.commit('mutdata','这是传递的参数') // pars 这是传递的参数
//如果要传递多个参数,用对象代替
//actions通过dispatch调用
this.$store.dispatch('setmut') // pars 更新数据
}
方法二、使用助手函数mapState()
// pages/index.vue
import { mapState } from 'vuex'
import { mapGetters } from 'vuex'
export default {
computed:{
...mapState({
info:state=>state.system.info
// 如果没有分模块直接用 ...mapState(['info']),
}),
...mapGetters(['getinfo']),
},
onLoad() {
console.log('store', this.info)
console.log('getters', this.getinfo)
}
}
在js文件中的调用方法
// 某js文件
import store from '@/store' //引入vuex
store.state.system.info
store.dispatch('setmut')