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