使用vuex和vue-resource预取数据

时间:2016-07-12 16:56:28

标签: vue.js vue-resource vuex

我正在构建一个遵循此结构的应用: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

由于

1 个答案:

答案 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
  }
}