繁体   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