簡體   English   中英

Vuex如何在數據道具中傳遞狀態/獲取器

[英]Vuex how to pass state/getter in data prop

我在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

我會使用Stephan-v的建議並刪除giveaways的本地副本。 但是我不知道您聲明額外giveaways具體原因是什么,因此這里提供了一種可行的解決方案:

在您的Dashboard.vue添加:

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

只需從數據對象中刪除giveaways屬性,然后將計算出的doneGiveAways重命名為giveaways即可完成。

在這種情況下,不需要本地組件giveaway數據屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM