使用vuex和axios獲取api數(shù)據(jù)

使用vuex,我們可以輕松管理狀態(tài)。因為如果您的組件需要共享和更新狀態(tài),那么就需要它。在本篇文章中,我將為您提供完整的vuex設(shè)置,其中包括帶有axios調(diào)用api獲取數(shù)據(jù)的示例。
因此,讓我們開始我們的vuex教程。現(xiàn)在,通過在終端中運(yùn)行以下代碼來創(chuàng)建Vue項目:
vue create vuex-app現(xiàn)在我們必須安裝vuex和axios。所以打開終端并一個接一個地運(yùn)行兩個命令。
npm install vuex//thennpm install axios
在您的 store 文件夾中,創(chuàng)建一個文件并命名 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})
現(xiàn)在,我們必須在您的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')
現(xiàn)在打開您的主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調(diào)用的Vuex完整指南示例。
評論
圖片
表情
