使用 vuex 和 vue-resource 预取数据
Pre-fetch data using vuex and vue-resource
我正在按照以下结构构建应用程序: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
?
谢谢
我刚弄明白:
在 /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
}
}
我正在按照以下结构构建应用程序: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
?
谢谢
我刚弄明白:
在 /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
}
}