我在Vuex操作中有一个操作,它提交了一个突变,它从组件中获取有效负载,也就是返回对象的索引的编号,它在Vuex js文件上工作得很好,这意味着在控制台上显示选定的项,正如我所说的,它从有效负载中获取索引,但在组件上,它给我Promise <Pending>,为什么会发生这种情况?目前,我还没有为我的Nuxt/Vue应用程序使用任何API,但我会的,现在,我只想知道为什么会发生这种情况,以及解决这个问题的最好方法是什么
下面是我的Vuex代码:
export const state = () => ({
articles: [
{
uid: 0,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/1.jpg',
link: '/articles/1',
},
{
uid: 1,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/2.jpg',
link: '/articles/2',
},
],
})
export const getters = {
getArticles(state) {
return state.articles
},
}
export const mutations = {
getSpeceficArticle(state, payload) {
return state.articles[payload]
},
}
export const actions = {
getSpeceficArticle({ commit }, payload) {
commit('getSpeceficArticle', payload)
},
}下面是我的组件代码:
<template>
<div class="article">
{{ getSpeceficArticle() }}
<div class="article__banner">
<img src="" alt="" />
</div>
<div class="article__text">
<p></p>
</div>
</div>
</template>
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
// computed: {},
methods: {
async getSpeceficArticle() {
return await this.$store.dispatch('articles/getSpeceficArticle', 0)
},
},
}
</script>发布于 2021-06-27 22:16:54
getter用于更新状态,它们类似于突变,但它们之间的主要区别是操作可以包括一些异步任务,如果你想在给定的索引处获得特定的文章,你应该使用一个名为getArticleByIndex的actions:
export const getters = {
getArticles(state) {
return state.articles
},
getArticleByIndex:: (state) => (index) => {
return state.articles[index]
}
}然后定义一个名为articleByIndex的计算属性:
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.$store.getters.articles.getArticleByIndex(0)
}
},
methods: {
},
}
</script>发布于 2021-06-28 10:49:50
如果你发现自己在使用Vuex中的很多getter/action等,并且它们开始变得有点冗长,你可以从Vuex中引入mapGetters,并将你的调用重命名为更方便的名称。所以你的脚本会变成,
<script>
import { mapGetters } from 'vuex'
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.getArticleByIndex(0)
}
},
methods: {
...mapGetters({
getArticleByIndex: 'articles/getArticleByIndex',
})
},
}
</script>您还可以将...mapGetters、...mapActions添加到计算节。
发布于 2021-06-27 22:17:24
由于在vuex操作中没有web服务调用,请尝试从组件中删除async和await关键字。稍后,当您添加一个webservice调用时,您可以使用resolve和reject将动作主体包装在新的Promise中,然后您可以在组件中使用async和await。如果这对你有效,请告诉我。
https://stackoverflow.com/questions/68151965
复制相似问题