vue.js - 使用 vuex 和 vue-resource 预取数据

标签 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

谢谢

最佳答案

我刚刚想通了:
/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
  }
}

关于vue.js - 使用 vuex 和 vue-resource 预取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38334910/

相关文章:

javascript - Vuejs : loading topojson from store and plot with d3

javascript - Vue.js 从另一个组件调用方法

vue.js - 在 Vuex 商店中使用 Vue-Resource;获取最大调用堆栈大小错误

vue.js - Vue.js : cannot redefine property: $url

javascript - 名为 '[DEFAULT]' 的 Firebase 应用程序已存在于 Vuex + Nuxt SPA 中

javascript - 如何将多个参数传递给 vuex getter?

vue.js - 防止删除或退格键触发@input 事件

javascript - 如何在 Vue.js 3 中制作自定义指令?

vue.js - webpack vue cli 在重新加载时清除浏览器控制台

javascript - Vuex 操作无法正常工作。显示错误 "signInWithEmailAndPassword failed: First argument "email"must be a valid string"