栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

15、axios的使用与数据的mock①

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

15、axios的使用与数据的mock①

具体的代码请移步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)先是轮播图的数据,我们把首页中的轮播图链接复制过来:

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

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

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

(1)安装express、axios

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

(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)

(3)devServer中添加before方法

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

四、使用axios获取mock数据

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

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/241131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号