Vue.js 3.x前端開發(fā)技術(shù)與實(shí)戰(zhàn) 課件 第11-13章 Vue3.x構(gòu)建工具-Vite;網(wǎng)絡(luò)請(qǐng)求庫(kù)Axios與JSONServer;Vue3+Element Plus實(shí)戰(zhàn)_第1頁(yè)
Vue.js 3.x前端開發(fā)技術(shù)與實(shí)戰(zhàn) 課件 第11-13章 Vue3.x構(gòu)建工具-Vite;網(wǎng)絡(luò)請(qǐng)求庫(kù)Axios與JSONServer;Vue3+Element Plus實(shí)戰(zhàn)_第2頁(yè)
Vue.js 3.x前端開發(fā)技術(shù)與實(shí)戰(zhàn) 課件 第11-13章 Vue3.x構(gòu)建工具-Vite;網(wǎng)絡(luò)請(qǐng)求庫(kù)Axios與JSONServer;Vue3+Element Plus實(shí)戰(zhàn)_第3頁(yè)
Vue.js 3.x前端開發(fā)技術(shù)與實(shí)戰(zhàn) 課件 第11-13章 Vue3.x構(gòu)建工具-Vite;網(wǎng)絡(luò)請(qǐng)求庫(kù)Axios與JSONServer;Vue3+Element Plus實(shí)戰(zhàn)_第4頁(yè)
Vue.js 3.x前端開發(fā)技術(shù)與實(shí)戰(zhàn) 課件 第11-13章 Vue3.x構(gòu)建工具-Vite;網(wǎng)絡(luò)請(qǐng)求庫(kù)Axios與JSONServer;Vue3+Element Plus實(shí)戰(zhàn)_第5頁(yè)
已閱讀5頁(yè),還剩50頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

教學(xué)目標(biāo)掌握Vite構(gòu)建工具的特性,學(xué)會(huì)安裝Vite。掌握Vite構(gòu)建前端項(xiàng)目的步驟和方法。熟悉Vite構(gòu)建前端項(xiàng)目的文檔結(jié)構(gòu)。學(xué)會(huì)使用Vite構(gòu)建不同規(guī)模的單頁(yè)前端項(xiàng)目。1第11章Vue3.x構(gòu)建工具-Vite(1學(xué)時(shí))211.1Vite構(gòu)建項(xiàng)目11.1.1Vite簡(jiǎn)介

Vite是Vue的作者尤雨溪開發(fā)的Web開發(fā)構(gòu)建工具,它是一個(gè)基于瀏覽器原生ES模塊導(dǎo)入的開發(fā)服務(wù)器,在開發(fā)環(huán)境下,利用瀏覽器去解析import,在服務(wù)器端按需編譯返回,完全跳過了打包這個(gè)概念,服務(wù)器隨啟隨用。同時(shí)不僅對(duì)Vue文件提供了支持,還支持熱更新,而且熱更新的速度不會(huì)隨著模塊增多而變慢。在生產(chǎn)環(huán)境下使用Rollup打包。

主要由兩部分組成:

一個(gè)開發(fā)服務(wù)器,它基于原生ES模塊。提供了豐富的內(nèi)建功能,如速度快到驚人的模塊熱更新(HMR)。

一套構(gòu)建指令。它使用Rollup打包你的代碼,并且它是預(yù)配置的,可輸出用于生產(chǎn)環(huán)境的高度優(yōu)化過的靜態(tài)資源。Vite主要特性有快速的冷啟動(dòng)、及時(shí)的熱模塊更新、真正的按需加載。注意:Vite需要Node.js版本v14.18+、v16+。然而,有些模板需要依賴更高的Node版本才能正常運(yùn)行,當(dāng)包管理器發(fā)出警告時(shí),請(qǐng)注意升級(jí)Node版本。

11.1.2搭建第一個(gè)Vite項(xiàng)目

可以通過附加的命令行選項(xiàng)直接指定項(xiàng)目名稱和需要使用的模板。例如,要構(gòu)建一個(gè)Vite+Vue3.2項(xiàng)目。執(zhí)行以下命令:#npm6.xnpmcreatevite@latestmy-vue-app--templatevue#npm7+,extradouble-dashisneeded:npmcreatevite@latestmy-vue-app--templatevue#yarnyarncreatevitemy-vue-app--templatevue#pnpmpnpmcreatevitemy-vue-app--templatevue311.1.2搭建第一個(gè)Vite項(xiàng)目

查看create-vite以獲取每個(gè)模板的更多細(xì)節(jié):vanilla、vanilla-ts、vue、vue-ts、react、react-ts、preact、preact-ts、lit、lit-ts、svelte、svelte-ts。

【例11-1】創(chuàng)建vite-app1項(xiàng)目。步驟如下:1.命令行輸入npmcreatevite(或npminitvite)。按照對(duì)話提示要求分別輸入項(xiàng)目名稱vite-app1、選擇框架vue、變體(vue/vue-ts),完成后按提示步驟啟動(dòng)開發(fā)服務(wù),如圖11-2所示。2.分別執(zhí)行cdvite-app1、npminstall、npmrundev等命令,完成后界面如圖11-3所示。

3在瀏覽器的URL中輸入http://localhost:3000/,頁(yè)面效果如圖11-4所示。直接使用下列附加命令行選項(xiàng)創(chuàng)建項(xiàng)目:npminitvitevite-app1--templatevuenpmcreatevitevite-app1--templatevue4

3.瀏覽器查看頁(yè)面效果。執(zhí)行完上述命令后,在瀏覽器的URL中輸入http://localhost:3000/,頁(yè)面效果如圖11-5所示,說明Vite創(chuàng)建Vue3項(xiàng)目完成。11.2Vite創(chuàng)建‘惠民早點(diǎn)’項(xiàng)目

Vite是下一代前端構(gòu)建工具,同樣可以使用Vite來構(gòu)建小型單面應(yīng)用項(xiàng)目。大型單頁(yè)應(yīng)用項(xiàng)目?jī)?yōu)先推薦使用VueCLI來創(chuàng)建。11.2.1創(chuàng)建默認(rèn)項(xiàng)目

【例11-2】創(chuàng)建項(xiàng)目vite-app2。步驟如下:

1.創(chuàng)建vite-app2項(xiàng)目。執(zhí)行以下命令:npmcreatevitevite-app2--templatevuenpminitvitevite-app2--templatevue

根據(jù)對(duì)話提示信息,依次輸入項(xiàng)目名稱、框架和JS類型,確定后完成項(xiàng)目構(gòu)建。2.安裝項(xiàng)目依賴和啟動(dòng)本地開發(fā)服務(wù)。順序執(zhí)行以下命令:cdvite-app2npminstallnpmrundev11.2.2更新完善項(xiàng)目

采用Vite創(chuàng)建Vue3.2小型項(xiàng)目,要求使用VueRouter實(shí)現(xiàn)路由導(dǎo)航,需要使用Vuex來實(shí)現(xiàn)狀態(tài)共享。‘惠民早點(diǎn)’單頁(yè)應(yīng)用頁(yè)面效果如圖11-6所示。對(duì)初始創(chuàng)建項(xiàng)目進(jìn)行功能性補(bǔ)充和完善,安裝相關(guān)依賴。51.安裝Vue4和VueRouter4npminstallvuexvue-router–D2.創(chuàng)建路由、倉(cāng)庫(kù)、視圖等相關(guān)子文件夾和修改或新建組件或JS文件。

在src子文件夾下分別建立store、router子文件夾,并在兩個(gè)子文件夾下新建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創(chuàng)建‘惠民早點(diǎn)’項(xiàng)目6狀態(tài)存儲(chǔ)配置文件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:

"豆?jié){",

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創(chuàng)建‘惠民早點(diǎn)’項(xiàng)目},

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文件。內(nèi)容如下: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>來實(shí)現(xiàn)。內(nèi)容如下:<script

setup>

import

HelloWorld

from

'./components/HelloWorld.vue'

</script>

<template>

<div

id="app">

<div

id="nav">

<router-link

to="/">惠民早點(diǎn)</router-link>

|

<router-link

to="/about">點(diǎn)餐助手</router-link>

</div>

<router-view

/>

</div>

11.2Vite創(chuàng)建‘惠民早點(diǎn)’項(xiàng)目</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子文件夾下創(chuàng)建views子文件夾,并在此文件夾下新建AboutView.vue和HomeView.vue文件。8AboutView.vue<template>

<div

id="app">

<img

alt="orderFood

logo"

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

/>

<OrderFood

message="點(diǎn)餐助手"

/>

</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創(chuàng)建‘惠民早點(diǎn)’項(xiàng)目HomeView.vue<template>

<div

class="home">

<img

alt="orderFood

logo"

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

/>

<HelloWorld

msg="歡迎惠顧'惠民早點(diǎn)'"

/>

</div>

</template>

<script

setup>

import

HelloWorld

from

"../components/HelloWorld.vue";

</script>

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

<div

class="hello">

<h3>{{

message

}}</h3>

<h3>*早餐名稱--單價(jià)-----數(shù)量----小計(jì)*</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">

小計(jì):{{

(food.price

*

food.amount).toFixed(2)

}}

</span>

</p>

</li>

</ul>

<div

class="display">

<p>點(diǎn)餐件數(shù):{{

total

}}

,點(diǎn)餐總價(jià):{{

orderSum

}}</p>

</div>

</div>

</template>

<!--

采用Vue3.2

新增<script

setup>

-->

11.2Vite創(chuàng)建‘惠民早點(diǎn)’項(xiàng)目<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文件。內(nèi)容如下:<!--

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++">

我為‘惠民早點(diǎn)’點(diǎn)贊數(shù)為:

{{

count

}}

</button>

</div>

</template>

<style

scoped>

a

{

color:

#42b983;}

</style>

11.2Vite創(chuàng)建‘惠民早點(diǎn)’項(xiàng)目

項(xiàng)目更新完成后,Vite會(huì)自動(dòng)進(jìn)行模塊熱更新。在瀏覽器中刷新頁(yè)面,效果如圖11-7和圖11-8所示。本章小結(jié)

本章主要Vite新前端構(gòu)建工具的特點(diǎn)和使用方法。講解使用Vite構(gòu)建前端項(xiàng)目常用命令和開發(fā)步驟。結(jié)合簡(jiǎn)易Vite+Vue3.2項(xiàng)目和Vite+Vue3.2+VueRouter+Vuex稍微復(fù)雜的項(xiàng)目,重點(diǎn)介紹如何使用Vite構(gòu)建前端單頁(yè)應(yīng)用項(xiàng)目。通過整個(gè)章節(jié)的學(xué)習(xí)與訓(xùn)練,能夠幫助和指導(dǎo)用戶和讀者去嘗試開發(fā)一個(gè)類似的小型項(xiàng)目,解決實(shí)際問題中一些小規(guī)模的業(yè)務(wù)的應(yīng)用需要。思考與拓展總結(jié)與提高教學(xué)目標(biāo)理解Axios特性和基礎(chǔ)應(yīng)用。結(jié)合vue-axios使用,學(xué)會(huì)配置全局使用Axios。理解Axios舉例和跨域請(qǐng)求數(shù)據(jù)。掌握J(rèn)SONServer安裝與啟動(dòng)方法。熟練使用Postman來完成接口測(cè)試。學(xué)會(huì)使用AxiosAPI與Axios攔截器。學(xué)會(huì)使用Vite+Axios構(gòu)建不同規(guī)模的單頁(yè)應(yīng)用。12第12章網(wǎng)絡(luò)請(qǐng)求庫(kù)Axios與JSONServer(1學(xué)時(shí))1312.1Axios概述12.1.1Axios簡(jiǎn)介Axios是一個(gè)基于Promise的HTTP庫(kù),類似于jQuery的AJAX,用于http請(qǐng)求??梢詰?yīng)用于瀏覽器端和node.js。既可以用于客戶端,也可以用于node.js編寫的服務(wù)端。目前所有主流瀏覽器均支持Axios。12.1.2Axios特性從瀏覽器中創(chuàng)建XMLHttpRequests。從node.js創(chuàng)建http請(qǐng)求。支持PromiseAPI。攔截請(qǐng)求和響應(yīng)。轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)。取消請(qǐng)求。自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)??蛻舳酥С址烙鵛SRF(Cross-SiteRequestForgery跨站請(qǐng)求偽造)。12.1.3Axios應(yīng)用

1.安裝與引用

在項(xiàng)目中可以使用npm、yarn或bower來安裝。可以通過CDN引用,或下載到本地通過script標(biāo)記來引用axios.min.js。安裝與引用格式如下:npminstall--saveaxiosvue-axiosyarnaddaxios<scriptsrc="/axios/dist/axios.min.js"></script><scriptsrc="/npm/axios/dist/axios.min.js"></script>2.項(xiàng)目中導(dǎo)入與使用

在項(xiàng)目的main.js文件中,通過下列語句來使用。代碼如下:1412.1.3Axios應(yīng)用//Vue2.6.x中引入axios并加到原型鏈中(選講)importaxiosfrom'axios';Vtotype.$axios=axios;//Vtotype.$http=axios;importQSfrom'qs';//用來序列化post類型的數(shù)據(jù),后面會(huì)提到Vtotype.qs=QS;

組件中使用this.$axios({…}).then().catch()來調(diào)用axios的相關(guān)方法。當(dāng)然也可以局部使用axios,需要在組件中導(dǎo)入axios,然后再使用axios的相關(guān)方法。3.結(jié)合vue-axios使用Vueaxios是axios集成到Vue.js的小包裝器,可以像插件一樣安裝:Vue.use(VueAxios);vue-axios包裝器將綁定axios

到Vue或this對(duì)象上。

將下面代碼加入main.js文件中。代碼如下:importVuefrom'vue'importaxiosfrom'axios'importVueAxiosfrom'vue-axios'Vue.use(VueAxios,axios)//使用順序不能錯(cuò)

組件中使用axios有兩種方式。分別如下:Vue.axios.get(api).then(response=>{

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

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

Vue3.x項(xiàng)目中,全局使用axios時(shí),需要對(duì)main.js文件進(jìn)行適當(dāng)修改。使用全局配置屬性app.config.globalProperties來重新定義。在各個(gè)組件中需要使用axios來實(shí)現(xiàn)http請(qǐng)求,需要使用provide()函數(shù)來全局提供,在子組件中需要使用注入inject()函數(shù)來使用axios的各個(gè)功能。具體代碼如下: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應(yīng)用同Vue版本中使用方式略有不同。Axios.get請(qǐng)求參數(shù)可以是一個(gè)參數(shù),也可以是兩個(gè)參數(shù)。一個(gè)參數(shù)時(shí),URL中通過“?”連接‘key=value’形式,來傳入?yún)?shù);通過“&”連接多個(gè)‘key=vlaue’形式,來傳入多個(gè)參數(shù)。兩個(gè)參數(shù)時(shí),第1個(gè)參數(shù)為URL前綴,如‘/user’;第2個(gè)參數(shù)為配置對(duì)象{},可以通過params對(duì)象傳遞參數(shù),如{params:{ID:12345}}。具體代碼如下:在Vue2.6.x中,代碼如下(選講)://

向具有指定ID的用戶發(fā)出請(qǐng)求

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

對(duì)象傳遞參數(shù)

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執(zhí)行g(shù)et請(qǐng)求Axios執(zhí)行g(shù)et().then().catch()請(qǐng)求。在不16

在Vue3.x中,執(zhí)行Axios的get().then().catch()請(qǐng)求。代碼如下://

向具有指定ID的用戶發(fā)出請(qǐng)求

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

.then(function

(response)

{console.log(response);

})

.catch(function

(error)

{console.log(error);

});

//

也可以通過

params

對(duì)象傳遞參數(shù)

axios.get('/user',

{params:

{

ID:

12345

}})

.then(function

(response)

{

console.log(response);

})

.catch(function

(error)

{

console.log(error);

});

12.2Axios舉例12.2.2執(zhí)行post請(qǐng)求Axios執(zhí)行post().then().catch()請(qǐng)求。在不同Vue版本中使用方式類似于get方法。以下主要介紹Vue3.x版本下的使用方式。執(zhí)行axios.post()方法時(shí)可以帶2個(gè)參數(shù),第1個(gè)參數(shù)為URL前綴,第2個(gè)參數(shù)為對(duì)象,如{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一次執(zhí)行多個(gè)請(qǐng)求問題導(dǎo)入:在實(shí)際Vue工程項(xiàng)目中,有時(shí)一次需要同時(shí)執(zhí)行多個(gè)請(qǐng)求(即并發(fā)請(qǐng)求),如何處理?解決方案:可以使用幫助函數(shù)來完成并發(fā)請(qǐng)求。其中axios.all()方法可以同時(shí)實(shí)現(xiàn)多個(gè)請(qǐng)求,其參數(shù)是1個(gè)數(shù)組,返回的結(jié)果也是1個(gè)數(shù)組。可以使用axios.spread()方法把返回結(jié)果分開拿出來。具體代碼如下:17function

getUserAccount(){

return

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

}

function

getUserPermissions(){

return

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

}

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

=>

{

//

這里response返回一個(gè)數(shù)組,里面裝了兩個(gè)請(qǐng)求的返回結(jié)果

console.log(response)

})

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

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

//當(dāng)這兩個(gè)請(qǐng)求都完成的時(shí)候會(huì)觸發(fā)這個(gè)函數(shù),兩個(gè)參數(shù)分別代表返回的結(jié)果

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

}))

12.3JSONServer與Postman12.3.1JSONServer簡(jiǎn)介

JSONServer是一款小巧的接口模擬(與Mock相似)工具,可以在一分鐘內(nèi)搭建一套具有Restful風(fēng)格的API,一般用在前后端分離后,前端人員可以不依賴API開發(fā),而在本地搭建一個(gè)JSON服務(wù),自己產(chǎn)生測(cè)試數(shù)據(jù)。JSONServer可以根據(jù)json數(shù)據(jù)建立一個(gè)完整的Web服務(wù)。只需指定一個(gè)json文件作為API的數(shù)據(jù)源即可,使用起來非常方便。12.2Axios舉例12.3.2JSONServer應(yīng)用

【例12-1】建立項(xiàng)目json-server-1。直接在當(dāng)前目錄下新建json-server-1子文件夾(不需要使用Vite或VueCLI來創(chuàng)建)。181.JSONServer安裝

可以在當(dāng)前項(xiàng)目下安裝,也可以全局安裝,全局安裝時(shí)加上參數(shù)“-g”即可。命令如下:npminstall[-g]json-server

安裝完成后可以查看版本號(hào),如果出現(xiàn)版本號(hào),如圖12-1所示,說明安裝成功。命令如下:json-server-v12.3.2JSONServer應(yīng)用2.創(chuàng)建db.json文件

在json-server-1子文件夾下創(chuàng)建db.json文件,作為提供API接口的數(shù)據(jù)源。文件內(nèi)容如下:{

"posts":

[

{

"id":

1,"title":

"Web前端開發(fā)技術(shù)","author":

"chujiuliang"

},

{

"id":

2,"title":

"Vue.js好學(xué)!","author":

"chujiuliang"}

],

"comments":

[

{

"title":

"JSON

Server",

"body":

"JSON

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

"id":

1,

"postId":

1

}

],

"profile":

{"name":

"chujiuliang"}

}

19

3.JSONServer啟動(dòng)服務(wù)

在命令行狀態(tài)下,切換到當(dāng)前文件夾下,執(zhí)行啟動(dòng)json-server命令。在當(dāng)前文件夾下,db.json文件不需要添加路徑,非當(dāng)前文件夾下,需要指定路徑。命令如下:

json-server--watch--port3000db.json

執(zhí)行命令后,結(jié)果如圖12-2所示。單擊資源(Resources)和首頁(yè)(Home)網(wǎng)址可以訪問。12.3.2JSONServer應(yīng)用

然后可以在瀏覽器的URL中輸入http://localhost:3000/,頁(yè)面效果如圖12-3所示。單擊頁(yè)面中“Resources”下的鏈接,可以分別查看請(qǐng)求返回的數(shù)據(jù)。例單擊“/posts”后,可以返回posts對(duì)象中數(shù)據(jù),如圖12-4所示。20

市場(chǎng)上接口測(cè)試工具有很多,如Mock.js、Jmeter、SoapUI、Fiddler、LoadRunner等,功能各有不同,可以根據(jù)項(xiàng)目開發(fā)需要選擇滿足業(yè)務(wù)要求的接口測(cè)試工具。Postman是一個(gè)接口測(cè)試工具。在進(jìn)行接口測(cè)試時(shí),Postman相當(dāng)于一個(gè)客戶端,它可以模擬用戶發(fā)起的各類HTTP請(qǐng)求,并將請(qǐng)求數(shù)據(jù)發(fā)送至服務(wù)端,獲取對(duì)應(yīng)的響應(yīng)數(shù)據(jù),來驗(yàn)證響應(yīng)數(shù)據(jù)是否和預(yù)期值相匹配,從而確保開發(fā)人員能夠及時(shí)處理接口中存在的Bug,保證上線產(chǎn)品的穩(wěn)定性和安全性。

Postman主要是用來模擬get、post、delete、put/patch等各種HTTP請(qǐng)求。它與瀏覽器的區(qū)別在于,有的瀏覽器不能輸出Json格式,而Postman更直觀接口返回的結(jié)果。12.3.3Postman-接口測(cè)試工具

安裝與使用方法比較簡(jiǎn)單。先從官網(wǎng)()上下載好安裝程序Postman-win64-9.20.3-Setup.exe,然后雙擊安裝即可。打開Postman,在“Send”按鈕左邊輸入JSONServer服務(wù)器地址,如http://localhost:3000,然后單擊“Send”按鈕,可以在下面的請(qǐng)求體“body”中看到請(qǐng)求返回的JSON數(shù)據(jù),如下圖12-5所示。21

跨域指瀏覽器不允許當(dāng)前頁(yè)面的所在的源去請(qǐng)求另一個(gè)源的數(shù)據(jù)。源指協(xié)議、端口、域名。出現(xiàn)跨越一般需要判斷3個(gè)方面:http協(xié)議、端口號(hào)、域名,三者若有一處不相同,那么就會(huì)出現(xiàn)跨域。

解決跨域問題需要配置一個(gè)代理服務(wù)器,通過代理服務(wù)器實(shí)現(xiàn)跨域請(qǐng)求。12.4.1VueCLI創(chuàng)建項(xiàng)目跨域配置

使用VueCLI創(chuàng)建的Vue項(xiàng)目,解決跨域問題,需要在vue.config.js文件中對(duì)devServer屬性進(jìn)行配置,定義為一個(gè)proxy對(duì)象,可以配置1個(gè)或多個(gè)代理。具體配置內(nèi)容如下:12.4跨域請(qǐng)求數(shù)據(jù)module.exports

=

{

devServer:

{

proxy:

{

'/api':

{

target:

'http://localhost:8080',

//

配置訪問的服務(wù)器地址

pathRewrite:

{

'^/api':

''

},

//

用于將請(qǐng)求中的‘/api’字符串替換為

ws:

true,

//

是否支持

webstocket,

默認(rèn)是

true

changeOrigin:

true

//

用于控制請(qǐng)求頭中的

host

值,

默認(rèn)是

ture

},

'/api2':

{

target:

'/mobile/',

//第三方接口

pathRewrite:

{

'^/api2':

''

},

ws:

true,

secure:true,//設(shè)置支持https協(xié)議的代理

changeOrigin:

true

}

}

}

}

完成代理服務(wù)器的相關(guān)配置,保存后立即生效,就需要通過AJAX請(qǐng)求訪問服務(wù)器了,一般Vue中使用的都是vue-axios和axios庫(kù)。2212.4.2Vite創(chuàng)建項(xiàng)目跨域配置

使用Vite創(chuàng)建的Vue項(xiàng)目,解決跨域問題,需要在vite.config.js文件的exportdefaultdefineConfig({})中對(duì)server屬性進(jìn)行配置,定義為一個(gè)proxy對(duì)象,定義代理路徑URL,其中路徑重寫rewrite屬性與vue.config.js中pathRewrite屬性配置方法略有不同。具體區(qū)別如下://vue.config.jspathRewrite:{

'^/api':

''

};//vite.config.jsrewrite:

(path)

=>

path.replace(/^\/api/,

"")vite.config.js具體配置內(nèi)容如下:import

{

defineConfig

}

from

"vite";

import

vue

from

"@vitejs/plugin-vue";

export

default

defineConfig({

base:

"./",

plugins:

[vue()],

server:

{

proxy:

{

"/api":

{

target:

"/mobile/",

//要請(qǐng)求的第三方接口前綴

changeOrigin:

true,

//開啟代理

secure:

true,

//

設(shè)置支持https協(xié)議的代理

ws:

true,

//

要代理

websockets,配置這個(gè)參數(shù)

rewrite:

(path)

=>

path.replace(/^\/api/,

""),

},

},

},

});

12.4跨域請(qǐng)求數(shù)據(jù)23

配置完成后,就可以在組件中使用axios.get("/api").then().catch()來執(zhí)行g(shù)et請(qǐng)求。其中"/api"就是在代理中設(shè)置的路徑,請(qǐng)求這個(gè)路徑就會(huì)跳轉(zhuǎn)到target指向的第三方接口。使用Postman采用get請(qǐng)求,在請(qǐng)求體的pramas中配置mobile、token、oid、mid等參數(shù),然后單擊“Send”按鈕,返回結(jié)果如圖12-6所示。部分參考代碼如下:axios.get("/api",{

params:{

mobile:"1530156xxxx",//手機(jī)號(hào)任意輸入

token:"6fb72cc7ccd21a13fb7ea7d814xxxxxx",//自行申請(qǐng)

oid:"5xxxx",//自行申請(qǐng)

mid:"1xxxx",//自行申請(qǐng)

}})

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

.catch((error)=>console.log(error));12.4跨域請(qǐng)求數(shù)據(jù)2412.5.1Axios可以通過配置(config)來發(fā)送請(qǐng)求axios(config)//發(fā)送一個(gè)post請(qǐng)求

,以12.3節(jié)中的db.json文件為數(shù)據(jù)源axios({

method:

'post',

//

post、get、put....

baseURL:'',

//

請(qǐng)求的域名,基本地址,公共的路徑

url:

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

//

請(qǐng)求的路徑

params:

{},

//

get參數(shù)會(huì)將請(qǐng)求參數(shù)拼接在url上

//

post會(huì)將請(qǐng)求參數(shù)放在請(qǐng)求體中

data:

{"id":3,"title":"POST請(qǐng)求試驗(yàn),"author":liming"

},

headers:

{},

//

設(shè)置請(qǐng)求頭,例如設(shè)置token等

timeout:

2000,

//

設(shè)置請(qǐng)求超時(shí)時(shí)長(zhǎng),單位ms

})

12.5AxiosAPI

使用Postman發(fā)送post請(qǐng)求,設(shè)置請(qǐng)求體body數(shù)據(jù)類型為“raw(JSON)”,定義一個(gè)JSON對(duì)象,然后單擊“Send”,響應(yīng)體中返回結(jié)果如圖12-7所示。原來db.json中posts數(shù)組有2個(gè)對(duì)象,執(zhí)行post請(qǐng)求成功后,新增1個(gè)對(duì)象。25axios(url[,config])//發(fā)送一個(gè)get請(qǐng)求(默認(rèn)的請(qǐng)求方式)

axios('/user/12345');

并發(fā)請(qǐng)求(concurrency),即是幫助處理并發(fā)請(qǐng)求的輔助函數(shù)。//iterable是一個(gè)可以迭代的參數(shù),如數(shù)組等

axios.all(iterable)

//callback要等到所有請(qǐng)求都完成才會(huì)執(zhí)行

axios.spread(callback)

12.5.2請(qǐng)求方式的別名。

為了方便起見,已經(jīng)為所有支持的請(qǐng)求方法提供了別名。axios.request(config)

//請(qǐng)求數(shù)據(jù)axios.get(url

[,config]

)

//獲取數(shù)據(jù)axios.delete(url

[,config])

//刪除數(shù)據(jù)axios.head(url

[,config])

//獲取報(bào)文首部axios.post(url

[,data

[,config]])

//提交數(shù)據(jù)axios.put(url

[,data

[,config]])

//更新數(shù)據(jù)axios.patch(url

[,data

[,config]])

//局部更新數(shù)據(jù)注意:當(dāng)使用別名方法時(shí),不需要在config中指定url、method和data屬性。其中參數(shù)帶[]表示不是必填參數(shù),沒有[]表示是必填參數(shù)。12.5AxiosAPI2612.5.3請(qǐng)求配置。

以下是創(chuàng)建請(qǐng)求時(shí)可以用的配置選項(xiàng)。只有url是必需的。如果沒有指定method,請(qǐng)求將默認(rèn)使用get方法(參見教材)。12.5AxiosAPI

【例12-2】創(chuàng)建json-server-2項(xiàng)目,使用Axios請(qǐng)求方式的別名完成“增刪改查”功能。代碼如下,頁(yè)面效果如圖12-8和圖12-9所示。

在本項(xiàng)目中需要使用JSONServer構(gòu)建JSON服務(wù)器,編寫HTML文件,實(shí)現(xiàn)對(duì)db.json文件的查詢(get)、修改(put)、添加(post)和刪除(delete)等操作。在HTML文件的<head>中需要引入vue.global.js和axios.min.js。27

首先,在當(dāng)前目錄下,創(chuàng)建項(xiàng)目文件夾json-server-2。然后在該文件夾下創(chuàng)建db.json文件,最終編寫axios-putpatch.html文件。1.創(chuàng)建db.json文件。內(nèi)容如下:{

"posts":

[

{"title":"Web前端開發(fā)技術(shù)","author":"儲(chǔ)久良","id":1}

{"title":

"Vue.js

前端框架技術(shù)與實(shí)戰(zhàn)",

"author":

"儲(chǔ)久良","id":

2},

{"title":

"Web前端開發(fā)技術(shù)實(shí)驗(yàn)與實(shí)踐","author":

"儲(chǔ)久良",

"id":

3},

]

}

2.啟動(dòng)JSONServer。

在當(dāng)前項(xiàng)目下安裝JSONServer(如果已全局安裝,則忽略該項(xiàng)安裝),并啟動(dòng)JSONServer,在瀏覽器的URL中輸入http://localhost:3000。命令如下:npminstalljson-serverjson-server--watchdb.json創(chuàng)建axios-putpatch.html文件。內(nèi)容如下:<!--

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請(qǐng)求方式的別名使用場(chǎng)景</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請(qǐng)求方式的別名的基礎(chǔ)應(yīng)用</h1>

<div>

<button

@click="getInit">發(fā)送GET請(qǐng)求</button>

<div

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

<button

@click="getReq">發(fā)送GET請(qǐng)求</button>

<div

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

<input

type="text"

v-model="title"

placeholder="請(qǐng)輸入標(biāo)題"

required>

<input

type="text"

v-model="author"

placeholder="請(qǐng)輸入作者"

required>

<button

@click="postReq(title,author)">發(fā)送POST請(qǐng)求</button>

<div

class="content"

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

<input

type="text"

v-model="id"

placeholder="請(qǐng)輸入需要修改對(duì)象的ID"

required><br>

<input

type="text"

v-model="titlemd"

placeholder="請(qǐng)輸入修改的標(biāo)題"

required>

<input

type="text"

v-model="authormd"

placeholder="請(qǐng)輸入修改的作者"

required>

<button

@click="putReq(id,titlemd,authormd)">發(fā)送PUT請(qǐng)求</button>

<div

class="content"

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

<input

type="text"

v-model="id_de"

placeholder="請(qǐng)輸入需要?jiǎng)h除對(duì)象的ID"

required>

<button

@click="deleteReq(id_de)">發(fā)送DELETE請(qǐng)求</button>

<div

class="content"

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

</div>

</div>

<script>

const

App

=

{

data()

{

return

{

getJson_start:'',

//

存放初始get數(shù)據(jù)

getJson:'',

//

存放當(dāng)前get的數(shù)據(jù)

postJson:'',

//

存放新添加的數(shù)據(jù)

putJson:'',

//

存放修改后的數(shù)據(jù)

title:'',

//

存放輸入標(biāo)題信息,用于POST請(qǐng)求

author:'',

//

存放輸入作者信息,用于POST請(qǐng)求

id:'',

//

存放更新對(duì)象的ID數(shù)據(jù)

titlemd:'',

//

存放新輸入修改標(biāo)題信息

authormd:'',

//

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

【例12-2】創(chuàng)建json-server-2項(xiàng)目29【例12-2】創(chuàng)建json-server-2項(xiàng)目

id_de:'',

//

存放刪除數(shù)據(jù)的ID數(shù)據(jù)

deleteTitle:'',

//

存放刪除數(shù)據(jù)后的提示信息

};

},

methods:

{

//

發(fā)送get請(qǐng)求,保存作為對(duì)比使用,不會(huì)自動(dòng)更新

getInit(){

axios.request({

//默認(rèn)為get請(qǐng)求,配置config

url:

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

}).then((res)

=>

{

this.getJson_start=res.data;

console.log('初始數(shù)據(jù)...');

});

},

//

1.發(fā)送GET請(qǐng)求,

查詢posts中所有數(shù)據(jù)

getReq()

{

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

=>

{

this.getJson=res.data;

console.log(res);

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

},

//

2.發(fā)送POST請(qǐng)求,

添加數(shù)據(jù)

postReq()

{

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

title:

this.title,

author:this.author

}).then((res)

=>

{

console.log(res);

this.postJson=res.data;

this.getReq()

//

添加數(shù)據(jù)后刷新原來請(qǐng)求數(shù)據(jù)

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

},

//

3.發(fā)送PUT請(qǐng)求,

修改文章,返回指定ID的對(duì)象數(shù)據(jù)

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.發(fā)送DELETE請(qǐng)求,

刪除文章

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");

//

創(chuàng)建實(shí)例并掛載

</script>

</body>

</html>

12.5.3Axios實(shí)例1.創(chuàng)建實(shí)例

可以使用自定義配置來創(chuàng)建axios的新實(shí)例。方法為axios.create([config])。具體代碼如下:var

instance

=

axios.create({

baseURL:

'/api/',

timeout:

1000,

headers:

{'X-Custom-Header':

'foobar'}

});

實(shí)例中參數(shù)說明。baseURL:設(shè)置請(qǐng)求的域名,基礎(chǔ)路徑、公共路徑等。timeout:設(shè)置請(qǐng)求超時(shí)時(shí)長(zhǎng),單位毫秒。headers:設(shè)置請(qǐng)求頭,例如設(shè)置token等。

2.實(shí)例方法

實(shí)例的方法與axios方法差不多。使用axios的實(shí)例對(duì)象instance,方法的返回值是一個(gè)Promise對(duì)象(then方法可以拿到異步請(qǐng)求的結(jié)果)。舉例如下:【例12-2】創(chuàng)建json-server-2項(xiàng)目31//一般創(chuàng)建axios實(shí)例時(shí),傳入一些默認(rèn)配置const

instance

=

axios.create({

baseURL:

'/api/',

timeout:

1000,

headers:

{'X-Custom-Header':

'foobar'}

});

//instance

實(shí)例和

axios對(duì)象功能基本差不多

instance({

method:

'GET',

//請(qǐng)求類型

url:

'/getJoke',

//URL

//設(shè)置請(qǐng)求體(即傳輸?shù)臄?shù)據(jù))

params:{

title:

"axios實(shí)例的方法",

author:

"longcheng"

}

}).then(response

=>

{

console.log(response);

})

12.5.3Axios實(shí)例

3.配置的默認(rèn)值(defaults)

可以指定將被用在各個(gè)請(qǐng)求的配置默認(rèn)值。設(shè)置全局的axios默認(rèn)值的方法如下:axios.defaults.baseURL='';mon['Authorization']=AUTH_TOKEN;axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';3212.6Axios攔截器

實(shí)際項(xiàng)目開發(fā)中,頁(yè)面發(fā)送http請(qǐng)求時(shí),通常需要對(duì)請(qǐng)求和其響應(yīng)進(jìn)行特定的預(yù)處理。問題導(dǎo)入:如果請(qǐng)求數(shù)非常多,單獨(dú)對(duì)每一個(gè)請(qǐng)求進(jìn)行處理會(huì)變得非常麻煩。解決方案:Axios為開發(fā)者提供攔截器(interceptors)API。攔截器分為請(qǐng)求request攔截器和響應(yīng)response攔截器。1.請(qǐng)求攔截器erceptors.request.use(

function

(config)

{

//

在發(fā)起請(qǐng)求請(qǐng)做一些業(yè)務(wù)處理

console.log(config.url);

//

設(shè)置請(qǐng)求頭中的

`mytoken`

字段

config.headers.mytoken

=

"axios-test";

return

config;

},

function

(error)

{

//

對(duì)請(qǐng)求失敗做處理

return

Promise.reject(error);

}

);

請(qǐng)求攔截適用場(chǎng)景:

可能是config中有一些信息是不符合服務(wù)器的要求。希望每次發(fā)送網(wǎng)絡(luò)請(qǐng)求,在界面可以顯示有一個(gè)請(qǐng)求的圖標(biāo),例旋轉(zhuǎn)的圓圈。一些網(wǎng)絡(luò)請(qǐng)求必須要有特殊信息,例如登錄(需要有token)。

2.響應(yīng)攔截器erceptors.response.use(function

(response)

{

//

對(duì)響應(yīng)數(shù)據(jù)做處理

return

response;

},

function

(error)

{

//

對(duì)響應(yīng)錯(cuò)誤做處理

return

Promise.reject(error);

});

響應(yīng)攔截通常適用場(chǎng)景:對(duì)響應(yīng)的數(shù)據(jù)進(jìn)行格式處理。3312.6Axios攔截器3.攔截器添加與移除

根據(jù)需要可以使用eject()來移除攔截器。代碼參考如下:constmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);可以為自定義axios實(shí)例使用use()來添加攔截器。代碼如下:constinstance=axios.create();erceptors.request.use(function(){/*...*/});12.7Axios應(yīng)用實(shí)戰(zhàn)12.7.1請(qǐng)求本地JSON數(shù)據(jù)

【例12-3】采用Vite構(gòu)建項(xiàng)目v

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論