Vuex如何在数据道具中传递state / getter

时间:2017-12-06 02:34:32

标签: javascript vue.js vuex

我在我的vuex

下使用axios从数据库中检索了我的数据
const state = {
    giveaways: null
}

const actions = {
    getGiveAways : ({commit}) =>{

        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {
            },
            config: 'JOSN'
        })
        .then(response=>{
            if(response.status == 200){
                //console.log(response.data.total_giveaways);
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveAways(state){
        return state.giveaways
    }
}

在我的Dashboard.vue中我有

import {mapState,mapGetters} from 'vuex'
export default{
    data: () => ({
        cards: [],
        giveaways: ''
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),
        doneGiveAways(){
            return this.$store.getters.doneGiveAways
        }
    },
    ready(){
        //giveaways: this.Giveaways
        //console.log(this.Giveaways);          
    },
    created(){
        const self = this
        this.cards[0].result_val = 2
        this.cards[2].result_val = 2;

    },
    mounted(){
        this.$store.dispatch('getGiveAways');
        console.log(this.giveaways);

    }
}

我的问题是我需要将mapState Giveaway中的值传递给我的返回数据giveaways: '',因此当页面触发时,我可以使用this.giveaways获取响应值。如果我只是在我的html中调用{{Giveaway}},它会显示值。但我需要制作类似this.giveaways = this.$store.state.Thresholds.giveaways

的内容

2 个答案:

答案 0 :(得分:2)

我会使用Stephan-v的推荐并删除giveaways的本地副本。但是我不知道你宣布giveaways的额外副本的具体原因是什么,所以这里有一个可行的解决方案:

Dashboard.vue添加:

export default {
    ...
    watch: {
        Giveaway(value) {
            this.giveaways = value
        }
    },
    ...
}

答案 1 :(得分:0)

只需从数据对象中删除giveaways属性,然后将计算出的doneGiveAways重命名为giveaways即可。

此方案中不需要本地组件giveaway数据属性。

相关问题