我要疯了,我有一个可以发送数据的工作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)
})
发布于 2017-05-11 12:57:15
使用箭头函数定义组件的mounted
生命周期挂钩。
根据文档
不要在实例属性或回调(例如
vm.$watch('a', newVal => this.myMethod())
)上使用箭头函数。由于箭头函数绑定到父上下文,所以this
将不是您所期望的Vue实例,而this.myMethod
将是未定义的。
您应该这样定义它:
mounted: function () {
this.$store.dispatch('getArticles');
}
或者,使用ECMAScript 5速记:
mounted() {
this.$store.dispatch('getArticles');
}
现在,您的dispatch
方法将被正确调用,填充您的项目数组。
https://stackoverflow.com/questions/43924900
复制