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,则在子组件中会报如下的错误:

这个时候我们就需要换个思路去实现,要在每个子组件中能够访问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()

使用:

<template>
    <view>
        <button @click="getList">点击</button>
    </view>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {mapState} from 'vuex'
  import {mapActions} from 'vuex'

  export default {
    
    mounted() {
      this.$store.dispatch('insertGoods', "abcd")
      this.insertGoods('vvvvv')// this.$store.dispatch的语法糖
    },

    methods: {
      getList() {
        //计算属性,获取state状态
        console.log(this.$store.state.goodsList);
        console.log(this.gettersGooosList);//语法糖
        
        //计算属性,从state派生一些状态,如果getters里面不需要派生,则直接返回和state取值一样
        console.log(this.$store.getters.goodsList);
        console.log(this.stateGoodsList);//语法糖
      },

      ...mapActions([
        'insertGoods'
      ])
    },
    
    
    computed: {
      ...mapGetters({
        gettersGooosList:'goodsList'
      }),//计算属性,如果不需要计算,则getters里面直接返回原值,就和State取值一样


      ...mapState({
        stateGoodsList:'goodsList'
      }),
    },


  }
</script>

<style lang="scss">
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值