我正在构建一个遵循此结构的应用:http://vuex.vuejs.org/en/structure.html
我的components/App.vue
喜欢这样:
<template>
<div id="app">
<course :courses="courses"></course>
</div>
</template>
<script>
import Course from './course.vue'
import { addCourses } from '../vuex/actions'
export default {
vuex: {
getters: {
courses: state => state.courses,
},
actions: {
addCourses,
}
},
ready() {
this.addCourses(this.fetchCourses())
},
components: { Course },
methods: {
fetchCourses() {
// what do I have to do here
}
}
}
</script>
如何获取数据并将其设置为state.courses
?
由于
答案 0 :(得分:3)
我刚想通了:
在/components/App.vue
ready
函数中,我只需调用:
ready() {
this.addCourses()
},
vuex/actions.js
中的:
import Vue from 'vue'
export const addCourses = ({ dispatch }) => {
Vue.http.get('/api/v1/courses')
.then(response => {
let courses = response.json()
courses.map(course => {
course.checked = false
return course
})
dispatch('ADD_COURSES', courses)
})
}
和vuex/store.js
:
const mutations = {
ADD_COURSES (state, courses) {
state.courses = courses
}
}