【问题标题】:vuex unknown action type: displayArticlesvuex 未知动作类型:displayArticles
【发布时间】:2019-10-16 04:15:47
【问题描述】:

为什么不显示来自jsonplaceholder 的json? 我在这里错过了什么吗?这只是我第一次使用 Vuex。

顺便说一句,我将文件分开以便我可以轻松调试它,我认为这对我来说是一个很好的做法,因为我计划在更大的项目中实现 vuex。 这是我的 index.js:

import Vue from 'vue';
import Vuex from 'vuex';
import articles from './modules/articles';

//Load Vuex
Vue.use(Vuex);

//Create store
export default new Vuex.Store({
    modules: {
        articles
    }
})

这是我的文章.js。

 import axios from 'axios';

//state
const state = {
    articles: []
};

//actions
const actions = {
    loadArticles({ commit }) {
        axios.get('https://jsonplaceholder.typicode.com/todos')
            .then(response => response.data)
            .then(articles => {
                commit('displayArticles', articles,
                console.log(articles))
            })
    }
};

//mutations
const mutations = {
    displayArticles(state, articles) {
        state.articles = articles;
    }
};

//export 
export default {
    state,
    getters,
    actions,
    mutations
};

最后是我的 home.vue,它将显示来自 vuex 的数据:

  <template>
  <section>
    <h1>HI</h1>
    <h1 v-for="article in articles" :key="article.id">{{article.id}}</h1>
  </section>
</template>

<script>
import { mapState } from "vuex";
export default {
  mounted() {
    this.$store.dispatch("displayArticles");
  },
  computed: mapState(["articles"])
};
</script>

【问题讨论】:

    标签: vue.js vuejs2 axios vuex


    【解决方案1】:

    您必须调度操作,因此您必须在 .vue 文件中编写:

    mounted() {
          this.$store.dispatch("loadArticles");
        },
    

    要获取组件中的文章列表,您应该在 Store 中使用 getter:

    const getters = {
      getArticles: state => {
        return state.articles;
      }
    

    计算出来的会是这样的:

        computed:{
          getArticlesFromStore(){
            return this.$store.getters.getArticles;
          }
        }
    

    然后你在你的 HTML 中调用计算出来的元素:

        <h1 v-for="article in getArticlesFromStore" :key="article.id">{{article.id}}</h1>
    

    【讨论】:

      【解决方案2】:

      您正在尝试调度突变。您需要使用带有突变的提交或将您的 displayArticles 移动到操作中。我想你的意思是调度 loadArticles?

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 2019-10-28
        • 2021-06-26
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-18
        相关资源
        最近更新 更多