【发布时间】: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: () => {更改为mounted: function () { -
vuejs.org/v2/guide/instance.html#Properties-and-Methods。向下滚动,直到看到有关箭头功能的警告。
标签: javascript vue.js axios vuex