简体   繁体   中英

Vuex how to pass state/getter in data prop

I retrieved my data from database using axios under my vuex

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
    }
}

In my Dashboard.vue I have

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);

    }
}

My problem is I need to pass the value from the mapState Giveaway to my returning data giveaways: '' so when page fires I can get the response value using this.giveaways . If I just call {{ Giveaway }} in my html it shows the value. But I need to make something like this.giveaways = this.$store.state.Thresholds.giveaways

I would use Stephan-v's recommendation and delete the local copy of giveaways . But I don't know what your specific reason is for declaring an extra copy of giveaways , so here is a solution that will work:

In your Dashboard.vue add:

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

Just delete the giveaways property from your data Object and rename the computed doneGiveAways to giveaways and you are done.

There is no need for a local component giveaway data property in this scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM