gpt4 book ai didi

javascript - 从组件内部调用的 vuex 调度上是否存在 "promise"类型的行为?

转载 作者:行者123 更新时间:2023-12-03 02:56:00 24 4
gpt4 key购买 nike

我正在学习vuex并遇到这个问题,在created()上我想从API获取数据,然后一旦完成我想从组件调用getter并将getter卡分配给组件的卡。我在created()中添加了一条评论,这样你就可以看到我想要得到的东西。调度时是否存在“ promise ”类型的行为?完成后做某事。提前致谢。我附上了代码的屏幕截图。

组件:

    <template>

<div class="container" :class="{'is-loading': isLoading}">
<h1>All Cards</h1>
<hr>
<section class="columns">
<app-card :card="card" v-for="card in cards" key="asdasd" />

</section>
</div>
</template>


<script>
import axios from 'axios'
import AppCard from './AppCard'

export default {
name: 'AppCards',
components: {
AppCard
},
data () {
return {
isLoading: true,
endpoint: `/cards.json`,
cards: []
}
},

created() {
this.$store.dispatch('fetchAllCards', this.endpoint)
// then(() => {
// this.cards = this.$store.getters.allCards (I want to get cards once action / mutation did its job and assign to this component's cards )
// })

}
}
</script>

Vuex:

import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import axios from 'axios'

Vue.use(Vuex)


const state = {
cards: null
}


const mutations = {
storeCards(state, fetchedCards) {
state.cards = fetchedCards
}
}


const actions = {
fetchAllCards({commit, state}, payload) {

axios.get(payload)
.then(response => {
const data = response.data
const cards = []

for(let key in data) {
if(data[key] !== null) {
const card = data[key]
card.id = key
cards.push(card)
}
}

commit('storeCards', cards)

})
.catch(e => {
console.log(e)
})

}
}


const getters = {
allCards(state) {
return state.cards
}
}


export default new Vuex.Store({
state,
mutations,
actions,
getters
})

最佳答案

与此同时,我在 Vue 的聊天中得到了答案,所以如果有人遇到这个问题,这里是答案

修改商店内的操作:

const actions = {
fetchAllCards({ commit }, payload) {
// return is here so we can use than inside comp (returns a promise)
return axios.get(payload).then( ({ data }) => {
const cards = [];
for(let key in data) {
if(data[key] !== null) {
const card = data[key]
card.id = key
cards.push(card)
}
}
commit('storeCards', cards)
})
}

修改了created()并计算以获取组件内的项目:

computed: {
cards() {
return this.$store.getters.allCards
}
},


created() {
this.$store.dispatch('fetchAllCards', this.endpoint) .then(() => {
this.isLoading = false
})
}

关于javascript - 从组件内部调用的 vuex 调度上是否存在 "promise"类型的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47620570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com