2

我正在按照以下结构构建一个应用程序: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

谢谢

4

1 回答 1

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
  }
}
于 2016-07-13T05:20:07.443 回答