Vue.js 3.x前端开发技术与实战 课件 第11-13章 Vue3.x构建工具-Vite;网络请求库Axios与JSONServer;Vue3+Element Plus实战_第1页
Vue.js 3.x前端开发技术与实战 课件 第11-13章 Vue3.x构建工具-Vite;网络请求库Axios与JSONServer;Vue3+Element Plus实战_第2页
Vue.js 3.x前端开发技术与实战 课件 第11-13章 Vue3.x构建工具-Vite;网络请求库Axios与JSONServer;Vue3+Element Plus实战_第3页
Vue.js 3.x前端开发技术与实战 课件 第11-13章 Vue3.x构建工具-Vite;网络请求库Axios与JSONServer;Vue3+Element Plus实战_第4页
Vue.js 3.x前端开发技术与实战 课件 第11-13章 Vue3.x构建工具-Vite;网络请求库Axios与JSONServer;Vue3+Element Plus实战_第5页
已阅读5页,还剩50页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

教学目标掌握Vite构建工具的特性,学会安装Vite。掌握Vite构建前端项目的步骤和方法。熟悉Vite构建前端项目的文档结构。学会使用Vite构建不同规模的单页前端项目。1第11章Vue3.x构建工具-Vite(1学时)211.1Vite构建项目11.1.1Vite简介

Vite是Vue的作者尤雨溪开发的Web开发构建工具,它是一个基于浏览器原生ES模块导入的开发服务器,在开发环境下,利用浏览器去解析import,在服务器端按需编译返回,完全跳过了打包这个概念,服务器随启随用。同时不仅对Vue文件提供了支持,还支持热更新,而且热更新的速度不会随着模块增多而变慢。在生产环境下使用Rollup打包。

主要由两部分组成:

一个开发服务器,它基于原生ES模块。提供了丰富的内建功能,如速度快到惊人的模块热更新(HMR)。

一套构建指令。它使用Rollup打包你的代码,并且它是预配置的,可输出用于生产环境的高度优化过的静态资源。Vite主要特性有快速的冷启动、及时的热模块更新、真正的按需加载。注意:Vite需要Node.js版本v14.18+、v16+。然而,有些模板需要依赖更高的Node版本才能正常运行,当包管理器发出警告时,请注意升级Node版本。

11.1.2搭建第一个Vite项目

可以通过附加的命令行选项直接指定项目名称和需要使用的模板。例如,要构建一个Vite+Vue3.2项目。执行以下命令:#npm6.xnpmcreatevite@latestmy-vue-app--templatevue#npm7+,extradouble-dashisneeded:npmcreatevite@latestmy-vue-app--templatevue#yarnyarncreatevitemy-vue-app--templatevue#pnpmpnpmcreatevitemy-vue-app--templatevue311.1.2搭建第一个Vite项目

查看create-vite以获取每个模板的更多细节:vanilla、vanilla-ts、vue、vue-ts、react、react-ts、preact、preact-ts、lit、lit-ts、svelte、svelte-ts。

【例11-1】创建vite-app1项目。步骤如下:1.命令行输入npmcreatevite(或npminitvite)。按照对话提示要求分别输入项目名称vite-app1、选择框架vue、变体(vue/vue-ts),完成后按提示步骤启动开发服务,如图11-2所示。2.分别执行cdvite-app1、npminstall、npmrundev等命令,完成后界面如图11-3所示。

3在浏览器的URL中输入http://localhost:3000/,页面效果如图11-4所示。直接使用下列附加命令行选项创建项目:npminitvitevite-app1--templatevuenpmcreatevitevite-app1--templatevue4

3.浏览器查看页面效果。执行完上述命令后,在浏览器的URL中输入http://localhost:3000/,页面效果如图11-5所示,说明Vite创建Vue3项目完成。11.2Vite创建‘惠民早点’项目

Vite是下一代前端构建工具,同样可以使用Vite来构建小型单面应用项目。大型单页应用项目优先推荐使用VueCLI来创建。11.2.1创建默认项目

【例11-2】创建项目vite-app2。步骤如下:

1.创建vite-app2项目。执行以下命令:npmcreatevitevite-app2--templatevuenpminitvitevite-app2--templatevue

根据对话提示信息,依次输入项目名称、框架和JS类型,确定后完成项目构建。2.安装项目依赖和启动本地开发服务。顺序执行以下命令:cdvite-app2npminstallnpmrundev11.2.2更新完善项目

采用Vite创建Vue3.2小型项目,要求使用VueRouter实现路由导航,需要使用Vuex来实现状态共享。‘惠民早点’单页应用页面效果如图11-6所示。对初始创建项目进行功能性补充和完善,安装相关依赖。51.安装Vue4和VueRouter4npminstallvuexvue-router–D2.创建路由、仓库、视图等相关子文件夹和修改或新建组件或JS文件。

在src子文件夹下分别建立store、router子文件夹,并在两个子文件夹下新建index.js文件。路由配置文件router/index.jsimport

{

createRouter,createWebHistory}

from

"vue-router";

import

About

from

"../views/AboutView.vue";

import

Home

from

"../views/HomeView.vue";

const

routes

=

[

{

path:

"/",

name:

"Home",

component:

Home,

},

{

path:

"/about",

name:

"About",

component:

About,

},

];

export

default

createRouter({

routes,

history:createWebHistory()

});

11.2Vite创建‘惠民早点’项目6状态存储配置文件store/index.jsimport

{createStore}

from

"vuex";

export

default

createStore({

state:

{

foods:

[

{

name:

"菜包",

price:

2.0,

amount:

0,

type:

0

},

{

name:

"肉包",

price:

3.0,

amount:

0,

type:

1

},

{

name:

"馒头",

price:

1.0,

amount:

0,

type:

2

},

{

name:

"豆浆",

price:

1.5,

amount:

0,

type:

3

},

{

name:

"牛奶",

price:

4.0,

amount:

0,

type:

4

},

{

name:

"稀饭",

price:

0.5,

amount:

0,

type:

5

},

],

total:

0,

orderSum:

0.0,

},

mutations:

{

addOrderAmount(state,

orderType)

{

state.foods[orderType].amount++;

},

reduceOrderAmount(state,

orderType)

{

state.foods[orderType].amount--;

11.2Vite创建‘惠民早点’项目},

addTotal(state)

{

state.total++;

},

reduceTotal(state)

{

state.total--;

},

totalSum(state)

{

state.orderSum

=

0;

for

(let

i

=

0;

i

<

state.foods.length;

i++)

{

state.orderSum

+=

state.foods[i].price

*

state.foods[i].amount;

}

state.orderSum

=

state.orderSum.toFixed(2);

},

},

actions:

{},

modules:

{},

});

7

修改main.js文件。内容如下:import

{

createApp

}

from

'vue'

import

App

from

'./App.vue'

import

router

from

'./router'

import

store

from

'./store'

createApp(App).use(router).use(store).mount('#app')

修改App.vue文件。

该单文件组件采用Vue3.2新增特性<scriptsetup>来实现。内容如下:<script

setup>

import

HelloWorld

from

'./components/HelloWorld.vue'

</script>

<template>

<div

id="app">

<div

id="nav">

<router-link

to="/">惠民早点</router-link>

|

<router-link

to="/about">点餐助手</router-link>

</div>

<router-view

/>

</div>

11.2Vite创建‘惠民早点’项目</template>

<style>

#app

{

font-family:

Avenir,

Helvetica,

Arial,

sans-serif;

-webkit-font-smoothing:

antialiased;

-moz-osx-font-smoothing:

grayscale;

text-align:

center;

color:

#2c3e50;

}

#nav

{

padding:

30px;

}

#nav

a

{

font-weight:

bold;

color:

#2c3e50;

}

#nav

a.router-link-exact-active

{

color:

#42b983;

}

</style>

在src子文件夹下创建views子文件夹,并在此文件夹下新建AboutView.vue和HomeView.vue文件。8AboutView.vue<template>

<div

id="app">

<img

alt="orderFood

logo"

src="/images/orderFood-logo2.jpg"

/>

<OrderFood

message="点餐助手"

/>

</div>

</template>

<script

setup>

import

OrderFood

from

"../components/OrderFood.vue";

</script>

<style>

img

{

width:

100px;

height:

100px;

border-radius:

10px;

border:

10px

solid

#8a8a8a;

}

</style>

11.2Vite创建‘惠民早点’项目HomeView.vue<template>

<div

class="home">

<img

alt="orderFood

logo"

src="/images/orderFood-logo.jpg"

/>

<HelloWorld

msg="欢迎惠顾'惠民早点'"

/>

</div>

</template>

<script

setup>

import

HelloWorld

from

"../components/HelloWorld.vue";

</script>

在components子文件夹下,新建OrderFood.vue文件。<template>

<div

class="hello">

<h3>{{

message

}}</h3>

<h3>*早餐名称--单价-----数量----小计*</h3>

<ul>

9<li

v-for="(food,

index)

in

foods"

:key="food.type">

<p>

{{

index

+

1

}}.{{

}}--{{

food.price.toFixed(2)

}}--

<button

v-show="food.amount

>

0"

@click="reduce(food.type)">-</button>

<span

v-show="food.amount

!=

0">

{{

food.amount

}}</span>

<button

@click="add(food.type)">+</button>

<span

v-show="food.amount

!=

0">

小计:{{

(food.price

*

food.amount).toFixed(2)

}}

</span>

</p>

</li>

</ul>

<div

class="display">

<p>点餐件数:{{

total

}}

,点餐总价:{{

orderSum

}}</p>

</div>

</div>

</template>

<!--

采用Vue3.2

新增<script

setup>

-->

11.2Vite创建‘惠民早点’项目<script

setup>

import

{

useStore

}

from

"vuex";

import

{

computed

}

from

"vue";

defineProps({

message:

String

});

const

store

=

useStore();

const

foods

=

computed(()

=>

store.state.foods);

const

total

=

computed(()

=>

store.state.total);

const

orderSum

=

computed(()

=>

store.state.orderSum);

function

add(n)

{

mit("addOrderAmount",

n);

mit("addTotal");

mit("totalSum");

}

function

reduce(n)

{

mit("reduceOrderAmount",

n);

mit("reduceTotal");

mit("totalSum");

}

</script>

<style

scoped>

.display

{

background:

#f1f2f3;

padding:

5px;}

button

{

margin:

2px

10px;}

li

{

list-style-type:

none;}

</style>

10修改HelloWord.vue文件。内容如下:<!--

Vue

3.2

新功能

SFCs

-->

<script

setup>

import

{

ref

}

from

"vue";

//

Vue

3.2中传值新API

defineProps({

msg:

String,

});

const

count

=

ref(0);

</script>

<template>

<div>

<h1>{{

msg

}}</h1>

<button

type="button"

@click="count++">

我为‘惠民早点’点赞数为:

{{

count

}}

</button>

</div>

</template>

<style

scoped>

a

{

color:

#42b983;}

</style>

11.2Vite创建‘惠民早点’项目

项目更新完成后,Vite会自动进行模块热更新。在浏览器中刷新页面,效果如图11-7和图11-8所示。本章小结

本章主要Vite新前端构建工具的特点和使用方法。讲解使用Vite构建前端项目常用命令和开发步骤。结合简易Vite+Vue3.2项目和Vite+Vue3.2+VueRouter+Vuex稍微复杂的项目,重点介绍如何使用Vite构建前端单页应用项目。通过整个章节的学习与训练,能够帮助和指导用户和读者去尝试开发一个类似的小型项目,解决实际问题中一些小规模的业务的应用需要。思考与拓展总结与提高教学目标理解Axios特性和基础应用。结合vue-axios使用,学会配置全局使用Axios。理解Axios举例和跨域请求数据。掌握JSONServer安装与启动方法。熟练使用Postman来完成接口测试。学会使用AxiosAPI与Axios拦截器。学会使用Vite+Axios构建不同规模的单页应用。12第12章网络请求库Axios与JSONServer(1学时)1312.1Axios概述12.1.1Axios简介Axios是一个基于Promise的HTTP库,类似于jQuery的AJAX,用于http请求。可以应用于浏览器端和node.js。既可以用于客户端,也可以用于node.js编写的服务端。目前所有主流浏览器均支持Axios。12.1.2Axios特性从浏览器中创建XMLHttpRequests。从node.js创建http请求。支持PromiseAPI。拦截请求和响应。转换请求数据和响应数据。取消请求。自动转换JSON数据。客户端支持防御XSRF(Cross-SiteRequestForgery跨站请求伪造)。12.1.3Axios应用

1.安装与引用

在项目中可以使用npm、yarn或bower来安装。可以通过CDN引用,或下载到本地通过script标记来引用axios.min.js。安装与引用格式如下:npminstall--saveaxiosvue-axiosyarnaddaxios<scriptsrc="/axios/dist/axios.min.js"></script><scriptsrc="/npm/axios/dist/axios.min.js"></script>2.项目中导入与使用

在项目的main.js文件中,通过下列语句来使用。代码如下:1412.1.3Axios应用//Vue2.6.x中引入axios并加到原型链中(选讲)importaxiosfrom'axios';Vtotype.$axios=axios;//Vtotype.$http=axios;importQSfrom'qs';//用来序列化post类型的数据,后面会提到Vtotype.qs=QS;

组件中使用this.$axios({…}).then().catch()来调用axios的相关方法。当然也可以局部使用axios,需要在组件中导入axios,然后再使用axios的相关方法。3.结合vue-axios使用Vueaxios是axios集成到Vue.js的小包装器,可以像插件一样安装:Vue.use(VueAxios);vue-axios包装器将绑定axios

到Vue或this对象上。

将下面代码加入main.js文件中。代码如下:importVuefrom'vue'importaxiosfrom'axios'importVueAxiosfrom'vue-axios'Vue.use(VueAxios,axios)//使用顺序不能错

组件中使用axios有两种方式。分别如下:Vue.axios.get(api).then(response=>{

console.log(response.data);});this.axios.get(api).then(response=>{

console.log(response.api);});

Vue3.x项目中,全局使用axios时,需要对main.js文件进行适当修改。使用全局配置属性app.config.globalProperties来重新定义。在各个组件中需要使用axios来实现http请求,需要使用provide()函数来全局提供,在子组件中需要使用注入inject()函数来使用axios的各个功能。具体代码如下:15import{createApp}from"vue";importAppfrom"./App.vue";importaxiosfrom"axios";importVueAxiosfrom"vue-axios";constapp=createApp(App);app.use(VueAxios,axios);app.provide("axios",app.config.globalProperties.axios)//写在mount()方法之前生效app.mount("#app");

子组件中使用axios的方法需要注入axios。代码如下:import{inject}from"vue";constaxios=inject("axios");//注入axiosaxios.get("/api").then((res)=>{console.log(res);}).catch((err)=>{console.log(err);});12.1.3Axios应用同Vue版本中使用方式略有不同。Axios.get请求参数可以是一个参数,也可以是两个参数。一个参数时,URL中通过“?”连接‘key=value’形式,来传入参数;通过“&”连接多个‘key=vlaue’形式,来传入多个参数。两个参数时,第1个参数为URL前缀,如‘/user’;第2个参数为配置对象{},可以通过params对象传递参数,如{params:{ID:12345}}。具体代码如下:在Vue2.6.x中,代码如下(选讲)://

向具有指定ID的用户发出请求

this.$axios.get('/user?ID=12345')

//this.$http.get('/user?ID=12345')

.then(function

(response)

{console.log(response);

})

.catch(function

(error)

{console.log(error);

});

//

也可以通过

params

对象传递参数

this.$axios.get('/user',

{

//this.$http.get('/user')

params:

{

ID:

12345

}

})

.then(function

(response)

{

console.log(response);

})

.catch(function

(error)

{

console.log(error);

});

12.2Axios举例12.2.1执行get请求Axios执行get().then().catch()请求。在不16

在Vue3.x中,执行Axios的get().then().catch()请求。代码如下://

向具有指定ID的用户发出请求

axios.get('/user?ID=12345')

.then(function

(response)

{console.log(response);

})

.catch(function

(error)

{console.log(error);

});

//

也可以通过

params

对象传递参数

axios.get('/user',

{params:

{

ID:

12345

}})

.then(function

(response)

{

console.log(response);

})

.catch(function

(error)

{

console.log(error);

});

12.2Axios举例12.2.2执行post请求Axios执行post().then().catch()请求。在不同Vue版本中使用方式类似于get方法。以下主要介绍Vue3.x版本下的使用方式。执行axios.post()方法时可以带2个参数,第1个参数为URL前缀,第2个参数为对象,如{key1:vlaue1,key2:value2,…}。具体代码如下:axios.post('/user',

{

firstName:

'Fred',

lastName:

'Flintstone'

})

.then(function

(response)

{console.log(response);

})

.catch(function

(error)

{

console.log(error);

});

12.2.3一次执行多个请求问题导入:在实际Vue工程项目中,有时一次需要同时执行多个请求(即并发请求),如何处理?解决方案:可以使用帮助函数来完成并发请求。其中axios.all()方法可以同时实现多个请求,其参数是1个数组,返回的结果也是1个数组。可以使用axios.spread()方法把返回结果分开拿出来。具体代码如下:17function

getUserAccount(){

return

axios.get('/user/12345');

}

function

getUserPermissions(){

return

axios.get('/user/12345/permissions');

}

axios.all([getUserAccount(),getUserPermissions()]).then((response)

=>

{

//

这里response返回一个数组,里面装了两个请求的返回结果

console.log(response)

})

axios.all([getUserAccount(),getUserPermissions()])

.then(axios.spread(function(acct,perms){

//当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果

console.log('acct'+acct)console.log('perms'+perms)

}))

12.3JSONServer与Postman12.3.1JSONServer简介

JSONServer是一款小巧的接口模拟(与Mock相似)工具,可以在一分钟内搭建一套具有Restful风格的API,一般用在前后端分离后,前端人员可以不依赖API开发,而在本地搭建一个JSON服务,自己产生测试数据。JSONServer可以根据json数据建立一个完整的Web服务。只需指定一个json文件作为API的数据源即可,使用起来非常方便。12.2Axios举例12.3.2JSONServer应用

【例12-1】建立项目json-server-1。直接在当前目录下新建json-server-1子文件夹(不需要使用Vite或VueCLI来创建)。181.JSONServer安装

可以在当前项目下安装,也可以全局安装,全局安装时加上参数“-g”即可。命令如下:npminstall[-g]json-server

安装完成后可以查看版本号,如果出现版本号,如图12-1所示,说明安装成功。命令如下:json-server-v12.3.2JSONServer应用2.创建db.json文件

在json-server-1子文件夹下创建db.json文件,作为提供API接口的数据源。文件内容如下:{

"posts":

[

{

"id":

1,"title":

"Web前端开发技术","author":

"chujiuliang"

},

{

"id":

2,"title":

"Vue.js好学!","author":

"chujiuliang"}

],

"comments":

[

{

"title":

"JSON

Server",

"body":

"JSON

Server是一款小巧的接口模拟(与mock相似)工具。",

"id":

1,

"postId":

1

}

],

"profile":

{"name":

"chujiuliang"}

}

19

3.JSONServer启动服务

在命令行状态下,切换到当前文件夹下,执行启动json-server命令。在当前文件夹下,db.json文件不需要添加路径,非当前文件夹下,需要指定路径。命令如下:

json-server--watch--port3000db.json

执行命令后,结果如图12-2所示。单击资源(Resources)和首页(Home)网址可以访问。12.3.2JSONServer应用

然后可以在浏览器的URL中输入http://localhost:3000/,页面效果如图12-3所示。单击页面中“Resources”下的链接,可以分别查看请求返回的数据。例单击“/posts”后,可以返回posts对象中数据,如图12-4所示。20

市场上接口测试工具有很多,如Mock.js、Jmeter、SoapUI、Fiddler、LoadRunner等,功能各有不同,可以根据项目开发需要选择满足业务要求的接口测试工具。Postman是一个接口测试工具。在进行接口测试时,Postman相当于一个客户端,它可以模拟用户发起的各类HTTP请求,并将请求数据发送至服务端,获取对应的响应数据,来验证响应数据是否和预期值相匹配,从而确保开发人员能够及时处理接口中存在的Bug,保证上线产品的稳定性和安全性。

Postman主要是用来模拟get、post、delete、put/patch等各种HTTP请求。它与浏览器的区别在于,有的浏览器不能输出Json格式,而Postman更直观接口返回的结果。12.3.3Postman-接口测试工具

安装与使用方法比较简单。先从官网()上下载好安装程序Postman-win64-9.20.3-Setup.exe,然后双击安装即可。打开Postman,在“Send”按钮左边输入JSONServer服务器地址,如http://localhost:3000,然后单击“Send”按钮,可以在下面的请求体“body”中看到请求返回的JSON数据,如下图12-5所示。21

跨域指浏览器不允许当前页面的所在的源去请求另一个源的数据。源指协议、端口、域名。出现跨越一般需要判断3个方面:http协议、端口号、域名,三者若有一处不相同,那么就会出现跨域。

解决跨域问题需要配置一个代理服务器,通过代理服务器实现跨域请求。12.4.1VueCLI创建项目跨域配置

使用VueCLI创建的Vue项目,解决跨域问题,需要在vue.config.js文件中对devServer属性进行配置,定义为一个proxy对象,可以配置1个或多个代理。具体配置内容如下:12.4跨域请求数据module.exports

=

{

devServer:

{

proxy:

{

'/api':

{

target:

'http://localhost:8080',

//

配置访问的服务器地址

pathRewrite:

{

'^/api':

''

},

//

用于将请求中的‘/api’字符串替换为

ws:

true,

//

是否支持

webstocket,

默认是

true

changeOrigin:

true

//

用于控制请求头中的

host

值,

默认是

ture

},

'/api2':

{

target:

'/mobile/',

//第三方接口

pathRewrite:

{

'^/api2':

''

},

ws:

true,

secure:true,//设置支持https协议的代理

changeOrigin:

true

}

}

}

}

完成代理服务器的相关配置,保存后立即生效,就需要通过AJAX请求访问服务器了,一般Vue中使用的都是vue-axios和axios库。2212.4.2Vite创建项目跨域配置

使用Vite创建的Vue项目,解决跨域问题,需要在vite.config.js文件的exportdefaultdefineConfig({})中对server属性进行配置,定义为一个proxy对象,定义代理路径URL,其中路径重写rewrite属性与vue.config.js中pathRewrite属性配置方法略有不同。具体区别如下://vue.config.jspathRewrite:{

'^/api':

''

};//vite.config.jsrewrite:

(path)

=>

path.replace(/^\/api/,

"")vite.config.js具体配置内容如下:import

{

defineConfig

}

from

"vite";

import

vue

from

"@vitejs/plugin-vue";

export

default

defineConfig({

base:

"./",

plugins:

[vue()],

server:

{

proxy:

{

"/api":

{

target:

"/mobile/",

//要请求的第三方接口前缀

changeOrigin:

true,

//开启代理

secure:

true,

//

设置支持https协议的代理

ws:

true,

//

要代理

websockets,配置这个参数

rewrite:

(path)

=>

path.replace(/^\/api/,

""),

},

},

},

});

12.4跨域请求数据23

配置完成后,就可以在组件中使用axios.get("/api").then().catch()来执行get请求。其中"/api"就是在代理中设置的路径,请求这个路径就会跳转到target指向的第三方接口。使用Postman采用get请求,在请求体的pramas中配置mobile、token、oid、mid等参数,然后单击“Send”按钮,返回结果如图12-6所示。部分参考代码如下:axios.get("/api",{

params:{

mobile:"1530156xxxx",//手机号任意输入

token:"6fb72cc7ccd21a13fb7ea7d814xxxxxx",//自行申请

oid:"5xxxx",//自行申请

mid:"1xxxx",//自行申请

}})

.then((res)=>{console.log(res);})

.catch((error)=>console.log(error));12.4跨域请求数据2412.5.1Axios可以通过配置(config)来发送请求axios(config)//发送一个post请求

,以12.3节中的db.json文件为数据源axios({

method:

'post',

//

post、get、put....

baseURL:'',

//

请求的域名,基本地址,公共的路径

url:

'http://localhost:3000/posts',

//

请求的路径

params:

{},

//

get参数会将请求参数拼接在url上

//

post会将请求参数放在请求体中

data:

{"id":3,"title":"POST请求试验,"author":liming"

},

headers:

{},

//

设置请求头,例如设置token等

timeout:

2000,

//

设置请求超时时长,单位ms

})

12.5AxiosAPI

使用Postman发送post请求,设置请求体body数据类型为“raw(JSON)”,定义一个JSON对象,然后单击“Send”,响应体中返回结果如图12-7所示。原来db.json中posts数组有2个对象,执行post请求成功后,新增1个对象。25axios(url[,config])//发送一个get请求(默认的请求方式)

axios('/user/12345');

并发请求(concurrency),即是帮助处理并发请求的辅助函数。//iterable是一个可以迭代的参数,如数组等

axios.all(iterable)

//callback要等到所有请求都完成才会执行

axios.spread(callback)

12.5.2请求方式的别名。

为了方便起见,已经为所有支持的请求方法提供了别名。axios.request(config)

//请求数据axios.get(url

[,config]

)

//获取数据axios.delete(url

[,config])

//删除数据axios.head(url

[,config])

//获取报文首部axios.post(url

[,data

[,config]])

//提交数据axios.put(url

[,data

[,config]])

//更新数据axios.patch(url

[,data

[,config]])

//局部更新数据注意:当使用别名方法时,不需要在config中指定url、method和data属性。其中参数带[]表示不是必填参数,没有[]表示是必填参数。12.5AxiosAPI2612.5.3请求配置。

以下是创建请求时可以用的配置选项。只有url是必需的。如果没有指定method,请求将默认使用get方法(参见教材)。12.5AxiosAPI

【例12-2】创建json-server-2项目,使用Axios请求方式的别名完成“增删改查”功能。代码如下,页面效果如图12-8和图12-9所示。

在本项目中需要使用JSONServer构建JSON服务器,编写HTML文件,实现对db.json文件的查询(get)、修改(put)、添加(post)和删除(delete)等操作。在HTML文件的<head>中需要引入vue.global.js和axios.min.js。27

首先,在当前目录下,创建项目文件夹json-server-2。然后在该文件夹下创建db.json文件,最终编写axios-putpatch.html文件。1.创建db.json文件。内容如下:{

"posts":

[

{"title":"Web前端开发技术","author":"储久良","id":1}

{"title":

"Vue.js

前端框架技术与实战",

"author":

"储久良","id":

2},

{"title":

"Web前端开发技术实验与实践","author":

"储久良",

"id":

3},

]

}

2.启动JSONServer。

在当前项目下安装JSONServer(如果已全局安装,则忽略该项安装),并启动JSONServer,在浏览器的URL中输入http://localhost:3000。命令如下:npminstalljson-serverjson-server--watchdb.json创建axios-putpatch.html文件。内容如下:<!--

axios-putpatch.html

-->

<!DOCTYPE

html>

<html

lang="en">

<head>

<meta

charset="UTF-8"

/>

<meta

http-equiv="X-UA-Compatible"

content="IE=edge"

/>

<meta

name="viewport"

content="width=device-width,

initial-scale=1.0"

/>

<title>Axios请求方式的别名使用场景</title>

<script

src="../../js/vue.global.js"></script>

<script

src="../../js/axios.min.js"></script>

<style

type="text/css">

.div

{width:

800px;height:

400px;border:

1px

solid

#222222;}

button

{border:

1px

dashed

#a8b8c8;width:

160px;height:

25px;

border-radius:

10px;font-size:

16px;margin:

5px

10px;}

.content{border:1px

dotted

#677078;border-radius:

8px;width:

800px;

padding:

10px;margin:

5px

2px;}

input{width:

200px;margin:

2px

10px;}

</style>

</head>

<body>

12.5AxiosAPI28

<div

id="app">

<h1>Axios请求方式的别名的基础应用</h1>

<div>

<button

@click="getInit">发送GET请求</button>

<div

class="content">{{getJson_start}}</div>

<button

@click="getReq">发送GET请求</button>

<div

class="content">{{getJson}}</div>

<input

type="text"

v-model="title"

placeholder="请输入标题"

required>

<input

type="text"

v-model="author"

placeholder="请输入作者"

required>

<button

@click="postReq(title,author)">发送POST请求</button>

<div

class="content"

id="post">{{postJson}}</div>

<input

type="text"

v-model="id"

placeholder="请输入需要修改对象的ID"

required><br>

<input

type="text"

v-model="titlemd"

placeholder="请输入修改的标题"

required>

<input

type="text"

v-model="authormd"

placeholder="请输入修改的作者"

required>

<button

@click="putReq(id,titlemd,authormd)">发送PUT请求</button>

<div

class="content"

id="put">{{putJson}}</div>

<input

type="text"

v-model="id_de"

placeholder="请输入需要删除对象的ID"

required>

<button

@click="deleteReq(id_de)">发送DELETE请求</button>

<div

class="content"

id="delete">{{deleteTitle}}</div>

</div>

</div>

<script>

const

App

=

{

data()

{

return

{

getJson_start:'',

//

存放初始get数据

getJson:'',

//

存放当前get的数据

postJson:'',

//

存放新添加的数据

putJson:'',

//

存放修改后的数据

title:'',

//

存放输入标题信息,用于POST请求

author:'',

//

存放输入作者信息,用于POST请求

id:'',

//

存放更新对象的ID数据

titlemd:'',

//

存放新输入修改标题信息

authormd:'',

//

存放新输入修改作者示信息

【例12-2】创建json-server-2项目29【例12-2】创建json-server-2项目

id_de:'',

//

存放删除数据的ID数据

deleteTitle:'',

//

存放删除数据后的提示信息

};

},

methods:

{

//

发送get请求,保存作为对比使用,不会自动更新

getInit(){

axios.request({

//默认为get请求,配置config

url:

"http://localhost:3000/posts/",

}).then((res)

=>

{

this.getJson_start=res.data;

console.log('初始数据...');

});

},

//

1.发送GET请求,

查询posts中所有数据

getReq()

{

axios.get("http://localhost:3000/posts/").then((res)

=>

{

this.getJson=res.data;

console.log(res);

}).catch((err)=>console.log(err));

},

//

2.发送POST请求,

添加数据

postReq()

{

axios.post("http://localhost:3000/posts",{

title:

this.title,

author:this.author

}).then((res)

=>

{

console.log(res);

this.postJson=res.data;

this.getReq()

//

添加数据后刷新原来请求数据

}).catch((err)=>{console.log(err);});

},

//

3.发送PUT请求,

修改文章,返回指定ID的对象数据

putReq(id,titlemd,authormd)

{

axios.put("http://localhost:3000/posts/"+id,{

title:

this.titlemd,

author:

this.authormd

}).then((res)

=>

{

this.putJson=res.data;

console.log(res);

}).catch((err)=>{console.log(err);});

},

30

//

4.发送DELETE请求,

删除文章

deleteReq(id)

{

axios.delete("http://localhost:3000/posts/"+id)

.then((res)

=>

{

this.deleteTitle='删除成功!';

this.getReq()

console.log(res.data);

}).catch((err)=>{console.log(err);});

},

},

};

Vue.createApp(App).mount("#app");

//

创建实例并挂载

</script>

</body>

</html>

12.5.3Axios实例1.创建实例

可以使用自定义配置来创建axios的新实例。方法为axios.create([config])。具体代码如下:var

instance

=

axios.create({

baseURL:

'/api/',

timeout:

1000,

headers:

{'X-Custom-Header':

'foobar'}

});

实例中参数说明。baseURL:设置请求的域名,基础路径、公共路径等。timeout:设置请求超时时长,单位毫秒。headers:设置请求头,例如设置token等。

2.实例方法

实例的方法与axios方法差不多。使用axios的实例对象instance,方法的返回值是一个Promise对象(then方法可以拿到异步请求的结果)。举例如下:【例12-2】创建json-server-2项目31//一般创建axios实例时,传入一些默认配置const

instance

=

axios.create({

baseURL:

'/api/',

timeout:

1000,

headers:

{'X-Custom-Header':

'foobar'}

});

//instance

实例和

axios对象功能基本差不多

instance({

method:

'GET',

//请求类型

url:

'/getJoke',

//URL

//设置请求体(即传输的数据)

params:{

title:

"axios实例的方法",

author:

"longcheng"

}

}).then(response

=>

{

console.log(response);

})

12.5.3Axios实例

3.配置的默认值(defaults)

可以指定将被用在各个请求的配置默认值。设置全局的axios默认值的方法如下:axios.defaults.baseURL='';mon['Authorization']=AUTH_TOKEN;axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';3212.6Axios拦截器

实际项目开发中,页面发送http请求时,通常需要对请求和其响应进行特定的预处理。问题导入:如果请求数非常多,单独对每一个请求进行处理会变得非常麻烦。解决方案:Axios为开发者提供拦截器(interceptors)API。拦截器分为请求request拦截器和响应response拦截器。1.请求拦截器erceptors.request.use(

function

(config)

{

//

在发起请求请做一些业务处理

console.log(config.url);

//

设置请求头中的

`mytoken`

字段

config.headers.mytoken

=

"axios-test";

return

config;

},

function

(error)

{

//

对请求失败做处理

return

Promise.reject(error);

}

);

请求拦截适用场景:

可能是config中有一些信息是不符合服务器的要求。希望每次发送网络请求,在界面可以显示有一个请求的图标,例旋转的圆圈。一些网络请求必须要有特殊信息,例如登录(需要有token)。

2.响应拦截器erceptors.response.use(function

(response)

{

//

对响应数据做处理

return

response;

},

function

(error)

{

//

对响应错误做处理

return

Promise.reject(error);

});

响应拦截通常适用场景:对响应的数据进行格式处理。3312.6Axios拦截器3.拦截器添加与移除

根据需要可以使用eject()来移除拦截器。代码参考如下:constmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);可以为自定义axios实例使用use()来添加拦截器。代码如下:constinstance=axios.create();erceptors.request.use(function(){/*...*/});12.7Axios应用实战12.7.1请求本地JSON数据

【例12-3】采用Vite构建项目v

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论