首先,问你们一个问题,vue是单页面应用,为何vuex在小程序的多页面中也可使用?vue
答:虽然小程序是多页的,但小程序的多页主要是指 视图层 是多个 webview,相互独立,可是 js 都是在同一个执行环境中的,因此在mpvue中能够直接使用vuex来管理状态。web
解决了这个困惑以后,你们是否是还有一个疑问,mpvue中能直接使用vuex吗?须要配置些什么吗?vuex
答:用vuex必然要用到vuex相关的一些辅助函数,如:mapGetters、mapMutations等。vue-cli
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()复制代码
正常思路你们应该是按照我上面这样的配置在main.js中引入vuex,而后在小程序中当使用到辅助函数时,你们会发现一个问题,报了个奇怪的错误,例:小程序
问题分析:bash
(1)、在通常的vue-cli + vuex项目中,主函数 main.js 中会将 store 对象提供给 “store” 选项,这样能够把 store 对象的实例注入全部的子组件中,从而在子组件中能够用this.$store.state.xxx、this.$store.dispatch 等来访问或操纵数据仓库中的数据,如:app
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})复制代码
(2)、在mpvue + vuex项目中,很遗憾不能经过上面那种方式来将store对象实例注入到每一个子组件中(至少我尝试N种配置不行),也就是说,在子组件中不能使用this.$store.xxx,从而致使辅助函数不能正确使用。这个时候咱们就须要换个思路去实现,要在每一个子组件中可以访问this.$store才行。既然咱们须要在子组件中用this.$store 访问store实例,那咱们直接在vue的原型上添加$store属性指向store对象不就行啦,一行代码便可:函数
Vue.prototype.$store = store复制代码
即:学习
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.prototype.$store = store
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()复制代码
能够看到,这个时候辅助函数已经生效了:ui
最后,给你们介绍一个小技巧,用于查看vuex相关数据,方便bug排查:
import Vue from 'vue'
import Vuex from 'vuex'
import * as getters from './getters'
import state from './state'
import mutations from './mutations'
import createLogger from 'vuex/dist/logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
getters,
state,
mutations,
strict: debug,
plugins: debug ? [createLogger()] : []
})复制代码
总结:
工做中,咱们须要触类旁通,能借鉴的东西,咱们要勇敢尝试,我相信读完这篇文章,你们对vuex在小程序中的使用的许多疑惑都消除了,mpvue+vuex的使用你们确定也都掌握了,若有问题欢迎你们给我留言,相互学习交流,才能共同进步!