如何使用axios从vuex中的API获取数据?

tej*_*owo 10 vue.js vuex

我从API laravel获取数据,这是我在state.js中的代码

import axios from 'axios'
import {apiPostGet} from '../api/api'
export default {
  data: axios({
    method: 'GET',
    url: apiPostGet('Kategori')
  }).then(
    response => {
      return response.data.kategori
    }
  ).catch(
    error => {
      return error.response
    }
  )
}
Run Code Online (Sandbox Code Playgroud)

这是我在gteeters.js中的代码

export default {
  datas: state => {
    return state.data
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我在index.js中的代码

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'

Vue.use(Vuex)

export default new Vuex.Store({
   state,
   getters
})
Run Code Online (Sandbox Code Playgroud)

这张照片来自开发工具vue js

AWo*_*olf 17

Datahook需要同步返回.您必须将加载添加到createdmounted只是将属性添加到数据/状态,因此反应性正在起作用.

使用Axios加载数据需要通过动作触发,因为它是异步的.突变需要同步运行.我添加了初始加载created.(mounted也会工作.)

我已经使用Vuex助手mapState将状态属性映射到组件.使用getter也可以工作,但mapState更容易编写.

请看下面的演示或这个小提琴.

同时取消注释小提琴中Vuex版本下面的代码并评论上面的应用程序,看看Axios如何使用Vuex以便更好地理解.

const URL = 'https://jsonplaceholder.typicode.com/posts';

const store = new Vuex.Store({
  state: {
    posts: [],
    loading: true
  },
  actions: {
    loadData({
      commit
    }) {
      axios.get(URL).then((response) => {
        // console.log(response.data, this)
        commit('updatePosts', response.data)
        commit('changeLoadingState', false)
      })
    }
  },
  mutations: {
    updatePosts(state, posts) {
      state.posts = posts
    },
    changeLoadingState(state, loading) {
      state.loading = loading
    }
  }
})

new Vue({
  el: '#app',
  computed: Vuex.mapState(['posts', 'loading']),
  store,
  created() {
    //console.log(this.$store)
    this.$store.dispatch('loadData') // dispatch loading
  }
})

/*
	//example with-out vuex
  
new Vue({
	el: '#app',
	data() {
  	return {
    	loading: true,
      posts: [] // add posts here so reactivity is working, also undefined would be OK
    }
  },
  created() {
  	//this.loading = true --> not needed already set in data
  	axios.get(URL).then((response) => {
    	// console.log(response.data, this)
      this.posts = response.data
      this.loading = false
    })
  }
})

*/
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<div id="app">
  <div v-if="loading">
    loading...
  </div>
  <div v-else>
    <ul>
      <li v-for="post in posts">
        <h1>
          {{post.title}}
        </h1>
        <p>
          {{post.body}}
        </p>
      </li>
    </ul>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)