我是靠谱客的博主 明理老鼠,这篇文章主要介绍Vuex异步获取数据的步骤,现在分享给大家,希望可以做个参考。

1、在api文件夹,新建个ajax.js文件(命名看个人习惯,如果没有该文件夹,可以新建一个),这个文件用于向服务器发请求

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import axios from "axios"; // 引入进度条 import nprogress from "nprogress"; // 引入进度条样式 import 'nprogress/nprogress.css' // console.log(nprogress); const requests = axios.create({ baseURL:'/api', timeout:5000 }); // 添加请求拦截器 requests.interceptors.request.use((config)=>{ nprogress.start() return config; }); // 添加响应拦截器 requests.interceptors.response.use( (response) =>{ // 2xx 范围内的状态码都会触发该函数。 // 对响应数据做点什么 nprogress.done(); return response.data; }, (error)=> { // 超出 2xx 范围的状态码都会触发该函数。 // 对响应错误做点什么 return Promise.reject(error); }) export default requests;

2、在api文件夹,新建个index.js文件(命名看个人习惯,如果没有该文件夹,可以新建一个),这个文件对api接口进行统一的管理,index.js文件主要用于数写请求接口,并对外暴露

复制代码
1
2
3
4
5
import requests from "./ajax"; // 请求地址:/api/product/getBaseCategoryList 请求方式:GET export const reqCategoryList = ()=> requests.get('/product/getBaseCategoryList')

3、在store文件夹,新建个index.js文件(命名看个人习惯,如果没有该文件夹,可以新建一个),采用模块化的

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 引入接口函数 import {reqCategoryList} from '@/api' // 存储数据 const state = { // state里面的初始值不能瞎写,服务器返回的是什么,起始值是什么 categoryList: [], } // 异步操作数据,将数据commit到mutations中 const actions = { // 通过API里面的接口函数调用,向服务器发请求,获取服务器的数据 async categoryList({commit}) { let result = await reqCategoryList(); if (result.code == 200) { commit('CATEGORYLIST', result.data)//在这里提交的名字一般大写 } }, } // 处理数据 const mutations = { CATEGORYLIST(state, categoryList) { state.categoryList = categoryList }, } // 计算属性 const getters = {} export default ({ state, actions, mutations, getters, })

4、在相应的组件挂载完毕后向服务器发起请求,此时vuex中已经存入页面的数据

复制代码
1
2
3
4
5
mounted(){ this.$store.dispatch("categoryList"); // console.log(this);VueComponent }

5、在相应的组件中,将数据从vuex中提取出来使用

复制代码
1
2
3
4
5
6
7
import { mapState } from "vuex"; computed: { ...mapState({ categoryList: (state) => state.home.categoryList, }) }

6、此时数据都在categoryList中,使用即可,如:

复制代码
1
2
<div class="item bo" v-for="(c1, index) in categoryList" :key="c1.categoryId"></div>

:在写完每一步后都要看看数据到底拿到了没有,如果一直写最后出错了不好寻找错误

最后

以上就是明理老鼠最近收集整理的关于Vuex异步获取数据的步骤的全部内容,更多相关Vuex异步获取数据内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部