javascript - Vuex 如何在 data prop 中传递 state/getter

标签 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

最佳答案

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

在你的 Dashboard.vue 添加:

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

关于javascript - Vuex 如何在 data prop 中传递 state/getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47665924/

相关文章:

javascript - 如何向网站添加加载屏幕

javascript - Cypress 无法识别我从/cypress 目录外部导入的模块

javascript - 如何在 vuetify 中动态添加/删除带有选择/自动完成值的新表单行?

javascript - 我的 vuejs 出现错误

javascript - 如何将字符串导出到另一个 Vue 文件?

javascript - ArrayController.addObjects 之后的 Emberjs Hook 称为 EmberJs 1.0.0

javascript - 为图像 slider 优化/制作更好的 JQuery 代码

javascript - 如何在 vuetify 弹出模式上放置要使用输入元素(v-select)固定的下拉项?

javascript - 将 vuex 存储导入 axios 和 app.js 文件

javascript - 何时再次通过 Vuex 从 API 获取数据以保持数据最新