我在 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
用于更新状态,它们就像突变,但它们之间的主要区别是操作可以包含一些异步任务,如果您想在给定索引处获取特定文章,您应该使用名为 getArticleByIndex
的 getter :
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>
关于vue.js - 为什么Vuex的action会返回一个promise<pending>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68151965/