为什么 Vuex 的 action returns a promise<pending>?

Why action of Vuex returns a promise<pending>?

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

actions 用于更新状态,它们就像突变一样,但它们之间的主要区别在于操作可以包含一些异步任务,如果你想在给定索引处获取特定文章,你应该使用getter 名为 getArticleByIndex :

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>

由于vuex action中没有web服务调用,尝试去掉组件中的async和await关键字。 稍后当你添加一个 web 服务调用时,你可以用 resolve 和 reject 将 action body 包装在新的 Promise 中,然后你可以在组件中使用 async 和 await 。让我知道这是否适合你。

@Mohammad 如果你发现自己在 Vuex 中使用了很多 getters/actions 等并且它们开始变得有点罗嗦,你可以从 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 添加到您的计算部分。