【问题标题】:vuex and axios debuggingvuex 和 axios 调试
【发布时间】:2017-10-11 00:23:18
【问题描述】:

我快疯了,我有一个发送数据的工作 api,我将它连接到一个 VueJS 应用程序,它工作正常。我正在尝试实现 Vuex,但我被卡住了。这是我的 store.js 文件

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios'
Vue.use(Vuex);

const state = {
        message: "I am groot",
        articles: []
    }
const getters = {
        getArticles: (state) => {
            return state.articles;
        }
    }
const actions = {
          getArticles: ({ commit }, data) => {
            axios.get('/articles').then( (articles) => {
                commit('GET_ARTICLES', articles);
                console.log(articles); // Trying to debug
            }, (err) => {
                console.log(err);
            })
          }
    }
const mutations =  {
        GET_ARTICLES: (state, {list}) => {
            state.articles = list;
        }   
    }
const store = new Vuex.Store({
    state,
    getters,
    mutations,
    actions,
    mutations
});
console.log(store.state.articles); // this lines works but data is empty
export default store

axios 调用中的 console.log 没有运行,并且 store.state.articles 为空。我肯定错过了什么。我只是想在页面加载时控制文章数据...

请帮忙,我快疯了:)

组件:

<template>
  <div class="container">
    <h1>Test component yo !</h1>
    <p>{{ message }}</p>
  </div>
</template>

<script>
    export default {
        name: 'Test',
        computed: {
            message() {
                return this.$store.state.message
            }
        },
        mounted: () => {
            this.$store.dispatch('getArticles')
        }

    }
</script>

App.js:

import Vue from 'vue';
import ArticlesViewer from './articles_viewer.vue';
import UserArticles from './user_articles.vue';
import App from './app.vue'
import store from './store'

new Vue({
  el: '#app-container',
  store,
  render: h => h(App)
})

【问题讨论】:

  • 你什么时候发送getArticles动作?
  • 我不,应该吗?
  • 是的,您已将state.articles 定义为一个空数组。在您进行 axios 调用之前它不会填充
  • mounted: () =&gt; {更改为mounted: function () {
  • vuejs.org/v2/guide/instance.html#Properties-and-Methods。向下滚动,直到看到有关箭头功能的警告。

标签: javascript vue.js axios vuex


【解决方案1】:

您使用箭头函数定义组件的mounted 生命周期钩子。

根据documentation

不要在实例属性或回调上使用箭头函数(例如vm.$watch('a', newVal =&gt; this.myMethod()))。由于箭头函数绑定到父上下文,this 不会像您期望的那样成为 Vue 实例,this.myMethod 将是未定义的。

你应该这样定义它:

mounted: function () {
  this.$store.dispatch('getArticles');
}

或者,使用 ECMAScript 5 速记:

mounted() {
  this.$store.dispatch('getArticles');
}

现在,您的 dispatch 方法将被正确调用,并填充您的文章数组。

【讨论】:

    猜你喜欢
    • 2019-12-06
    • 2020-09-20
    • 2020-07-13
    • 2021-05-22
    • 2020-01-05
    • 2019-05-31
    • 2019-05-08
    • 2021-05-03
    • 2019-10-16
    相关资源
    最近更新 更多