vuexActions总结

拟墨画扇 提交于 2020-01-15 21:04:23

总结

写法

    import Vue from 'vue'
    import Vuex from 'vuex'
    import axios from 'axios'
    Vue.use(Vuex)

    const store = new Vuex.Store({
        state: {
            // 购物车数据
            shopCart: [
                {
                    name: '卫龙大辣条',
                    price: '¥1.25'
                },
                {
                    name: '鱼豆腐',
                    price: '¥2'
                }
            ]
        },
        getters: {},
        mutations: {
            // 改变购物车数据的函数
            // 第一个参数 state就是 Store中的state 第二个参数是执行函数是 用户传递的数据 第三用来判断是否清空购物车 如果是true则清空购物车
            handleShopCart(state, data) {
                state.shopCart = data
            }
        },
        actions: {
            buyNow({commit, state}) {
                return new Promise((resolve, reject) => {
                    axios.get('购买按钮对应的请求地址').then(res => {
                        commit('handleShopCart', [])
                        resolve('这里是用户购买成功后要传递的数据')
                    }).catch(err => {
                        commit('handleShopCart', state.shopCart)
                        reject('这里是用户购买失败后要传递的数据')
                    })
                })
                
            }
        }
    })

用法

//  例如在created中使用该函数
created() {
    this.$store.dispatch('buyNow', '要传递得参数')
}
import {mapActions} from 'vuex'
created() {
    // 如果 actions函数没有使用promise则可以不用then 直接调用该函数就行
    this.buyNow().then(res => {
        console.log(res)
    })
},
methods: {
    ...mapActions([
        'buyNow'
    ])
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!