vuex---mapGetters和mapActions

若有多个getter时,可用...mapGetters([ ]),需要先export引入,且是es6语法,需要安装bable插件

...mapActions([ ])同理;

这样写可以简化代码;

具体用法如下:

// productListOne.vue中

<script>
import {mapGetters} from 'vuex'
import {mapActions} from 'vuex'
export default {
  
  // 通过调用方法获取store.js里的数据
  computed: {
    products() {
      return this.$store.state.products
    },
    // saleProducts() {
    //   return this.$store.getters.saleProducts;
    // }

    // 若有多个getter时,可用...mapGetters([]),需要先export引入,且是es6语法
    ...mapGetters([
      "saleProducts",
      // "akjsv",
      // "akjsv",
      
    ])
    
  },
  methods: {
    // reducePrice: function(amount){
    //   // this.$store.state.products.forEach(product => {
    //   //   product.price -= 1;
    //   // });
    //   // this.$store.commit('reducePrice')
    //   this.$store.dispatch("reducePrice",amount)  // 要想走action里的方法,此刻就需要dispatch
    // }

    // 若有多个action时,可用...mapActions([])
    ...mapActions([
      "reducePrice",
      // "kgfjag",
      // "kgfjag",
    ])
    
  }
}
</script>

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序中管理和维护状态,例如用户信息、购物车、主题等。Vuex将状态存储在一个集中的存储库中,称为storeVuex的核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store中获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序中使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件中使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例中,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store中获取count状态。在Vue组件中,我们使用mapGetters和mapActions帮助程序将getteraction映射到组件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值