使用vuex和axios获取api数据

使用vuex,我们可以轻松管理状态。因为如果您的组件需要共享和更新状态,那么就需要它。在本篇文章中,我将为您提供完整的vuex设置,其中包括带有axios调用api获取数据的示例。
因此,让我们开始我们的vuex教程。现在,通过在终端中运行以下代码来创建Vue项目:
vue create vuex-app现在我们必须安装vuex和axios。所以打开终端并一个接一个地运行两个命令。
npm install vuex//thennpm install axios
在您的 store 文件夹中,创建一个文件并命名 index.js 。
├── index.html└── src├── components├── App.vue└──store└── index.js
接下来,在 store/index.js 文件中输入以下代码:
import axios from 'axios'import Vuex from 'vuex'import Vue from 'vue'//load VuexVue.use(Vuex);//to handle stateconst state = {posts: []}//to handle stateconst getters = {}//to handle actionsconst actions = {getPosts({ commit }) {axios.get('https://jsonplaceholder.typicode.com/posts').then(response => {commit('SET_POSTS', response.data)})}}//to handle mutationsconst mutations = {SET_POSTS(state, posts) {state.posts = posts}}//export store moduleexport default new Vuex.Store({state,getters,actions,mutations})
现在,我们必须在您的main.js文件中注册我们的store :
import Vue from 'vue'import App from './App.vue'import store from './store'Vue.config.productionTip = falsenew Vue({store,render: h => h(App),}).$mount('#app')
现在打开您的主App.vue文件,输入以下代码:
<template><div id="app"><h1>{{ msg }}</h1><div><ul v-for='post in posts' :key='post.id'><li>Post Title: {{post.title}}</li></ul></div></div></template><script>import { mapGetters } from 'vuex';export default {name: 'App',data () {return {msg: 'We are learning vuex!!'}},computed: {computed: mapGetters(['allPosts']),},mounted() {this.$store.dispatch("getPosts");}}</script>
这就是使用Axios Api调用的Vuex完整指南示例。
评论
