15、axios的使用与数据的mock1

时间:2022-06-09
本文章向大家介绍15、axios的使用与数据的mock1,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

具体的代码请移步github GitHub:https://github.com/Ewall1106/mall(请选择分支15)

一、axios官方文档基本阅读

我们先从官方实例上上看看axios的用法:https://github.com/axios/axios

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
    .then(function (response) {
    console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

// Optionally the request above could also be done as
axios.get('/user', {
        params: {
            ID: 12345
        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

// Want to use async/await? Add the `async` keyword to your outer function/method.async function getUser() {
    try {
        const response = await axios.get('/user?ID=12345');
        console.log(response);
    } catch (error) {
        console.error(error);
    }
}

上面的记个大概就好,我们动手实践一波。

二、新建mock.json

1、我们先在static文件夹下新建一个mock文件,里面放上我们首页所需要的数据 (1)先是轮播图的数据,我们把首页中的轮播图链接复制过来:

mock数据

(2)然后是分类的icon图片和推荐模块相关数据

mock数据

三、axios的安装和数据mock的一些配置

1、然后我们动手先安装一波axiosexpress,为什么要用到express,因为我们数据的mock中需要用到express框架实现,后面我们在详细讲解expres。

(1)安装express、axios

$ npm install express  --save
$ npm install axios  --save

install express and axios

(2)在webpack.dev.conf.js的头部中引入

// mock数据
const express = require('express')
const app = express()
var appData = require('../static/mock/mock.json')
var router = express.Router()
// 通过路由请求本地数据
app.use('/api', router)

config配置

(3)devServer中添加before方法

// 添加before方法
before(app) {
    app.get('/api/appData', (req, res) => {
        res.json({
            errno: 0,
            data: appData
        })
    })
}

before()

四、使用axios获取mock数据

1、我们进入hom.vue页面先引入axios;

2、然后我们在methods中写个函数:用axios获取首页数据并打印,然后当vue生命周期为mounted阶段时调用它:

使用axios获取数据

3、最后我们进入浏览器中看看数据是不是打印出来了

浏览器console

ok,我们mock的数据都拿到了。到了这一步,接下来就简单了,无非是把值传给组件,然后将数据渲染到页面上,这个我们下篇讲。

参考学习 https://github.com/axios/axios https://github.com/Ewall1106/mall https://www.jianshu.com/p/986821d35988 https://www.jianshu.com/p/4f92c4461e3d https://www.jianshu.com/p/004b73f3f589