mpvue中使用vuex爬坑过程

1、辅助函数不能使用

vuex的辅助函数有mapState、mapGetters、mapMutations、mapActions。

我们在子组件经常用到很多状态量,为了避免过分的使用this.$store.state.xxx、this.$store.dispatch导致的冗余问题,我们用辅助函数来使代码变得简洁易读,它就相当于语法糖似的,实际上还会映射为this.$store.xxx

在一般的vue-cli + vuex项目中,主函数 main.js 中会将 store 对象提供给 “store” 选项,这样可以把 store 对象的实例注入所有的子组件中,从而在子组件中可以用this.$store.state.xxx、this.$store.dispatch 等来访问或操纵数据仓库中的数据。

但是在mpvue + vuex项目中,不能通过上面那种方式来将store对象实例注入到每个子组件中,也就是说,在子组件中不能使用this.$store.xxx,从而导致辅助函数不能正确使用。

store对象不能注入到子组件中,在子组件中不能使用this.$store,如果使用了vuex辅助函数mapMutations与mapGetters,则在子组件中会报如下的错误:

mpvue中使用vuex爬坑过程_第1张图片

这个时候我们就需要换个思路去实现,要在每个子组件中能够访问this.$store才行。

解决方法:

将store对象通过$store属性添加到vue原型上,即:Vue.prototype.$store = store

在main.js中,需要做一些更改:

import Vue from 'vue'
import App from './App'

import store from './store/index'

import Fly from 'flyio/dist/npm/wx'
let fly = new Fly
Vue.prototype.$fly = fly

Vue.config.productionTip = false
App.mpType = 'app'

Vue.prototype.$store = store

const app = new Vue(App)
app.$mount()

使用:






 

你可能感兴趣的:(VUE)