課程鏈接
4.Vue中的Ajax
4.1.vue腳手架配置代理
4.1.1.方法一
? 在vue.config.js中添加如下配置:
devServer:{
proxy:"http://localhost:5000"
}
說明:
- 優(yōu)點(diǎn):配置簡(jiǎn)單,請(qǐng)求資源時(shí)直接發(fā)給前端(8080)即可。
- 缺點(diǎn):不能配置多個(gè)代理,不能靈活的控制請(qǐng)求是否走代理。
- 工作方式:若按照上述配置代理,當(dāng)請(qǐng)求了前端不存在的資源時(shí),那么該請(qǐng)求會(huì)轉(zhuǎn)發(fā)給服務(wù)器 (優(yōu)先匹配前端資源【public下的資源】)
4.1.2.方法二
? 編寫vue.config.js配置具體代理規(guī)則:
module.exports = {
devServer: {
proxy: {
'/api1': {// 匹配所有以 '/api1'開頭的請(qǐng)求路徑
target: 'http://localhost:5000',// 代理目標(biāo)的基礎(chǔ)路徑
changeOrigin: true,//用于控制請(qǐng)求頭中的host值
pathRewrite: {'^/api1': ''}
},
'/api2': {// 匹配所有以 '/api2'開頭的請(qǐng)求路徑
target: 'http://localhost:5001',// 代理目標(biāo)的基礎(chǔ)路徑
changeOrigin: true,//用于控制請(qǐng)求頭中的host值
pathRewrite: {'^/api2': ''}
}
}
}
}
/*
changeOrigin設(shè)置為true時(shí),服務(wù)器收到的請(qǐng)求頭中的host為:localhost:5000
changeOrigin設(shè)置為false時(shí),服務(wù)器收到的請(qǐng)求頭中的host為:localhost:8080
changeOrigin默認(rèn)值為true
*/
說明:
- 優(yōu)點(diǎn):可以配置多個(gè)代理,且可以靈活的控制請(qǐng)求是否走代理。
- 缺點(diǎn):配置略微繁瑣,請(qǐng)求資源時(shí)必須加前綴。
4.2.插槽
-
作用:讓父組件可以向子組件指定位置插入html結(jié)構(gòu),也是一種組件間通信的方式,適用于 父組件 ===> 子組件 。
-
分類:默認(rèn)插槽、具名插槽、作用域插槽
-
使用方式:
-
默認(rèn)插槽:
父組件中: <Category> <div>html結(jié)構(gòu)1</div> </Category> 子組件中: <template> <div> <!-- 定義插槽 --> <slot>插槽默認(rèn)內(nèi)容...</slot> </div> </template>
-
具名插槽:
父組件中: <Category> <template slot="center"> <div>html結(jié)構(gòu)1</div> </template> <!-- <template slot="footer"></template> --> <template v-slot:footer><!--v-slot只能配合template使用--> <div>html結(jié)構(gòu)2</div> </template> </Category> 子組件中: <template> <div> <!-- 定義插槽 --> <slot name="center">插槽默認(rèn)內(nèi)容...</slot> <slot name="footer">插槽默認(rèn)內(nèi)容...</slot> </div> </template>
-
作用域插槽:
-
理解:數(shù)據(jù)在組件的自身,但根據(jù)數(shù)據(jù)生成的結(jié)構(gòu)需要組件的使用者來決定。(games數(shù)據(jù)在Category組件中,但使用數(shù)據(jù)所遍歷出來的結(jié)構(gòu)由App組件決定)
-
具體編碼:
父組件中: <Category> <template scope="scopeData"> <!-- 生成的是ul列表 --> <ul> <li v-for="g in scopeData.games" :key="g">{{g}}</li> </ul> </template> </Category> <Category> <template slot-scope="scopeData"> <!-- 生成的是h4標(biāo)題 --> <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4> </template> </Category> 子組件中: <template> <div> <slot :games="games"></slot> </div> </template> <script> export default { name:'Category', props:['title'], //數(shù)據(jù)在子組件自身 data() { return { games:['紅色警戒','穿越火線','勁舞團(tuán)','超級(jí)瑪麗'] } }, } </script>
-
作用域如何理解:主要在于子組件slot標(biāo)簽中的:games=‘games’ 和父組件的scope=‘xxx’
-
5.Vuex
5.1.理解Vuex
5.1.1.概念
? 在Vue中實(shí)現(xiàn)集中式狀態(tài)(數(shù)據(jù))管理的一個(gè)Vue插件,對(duì)vue應(yīng)用中多個(gè)組件的共享狀態(tài)進(jìn)行集中式的管理(讀/寫),也是一種組件間通信的方式,且適用于任意組件間通信。
5.1.2.何時(shí)使用?
? 多個(gè)組件需要共享數(shù)據(jù)時(shí)
5.1.3.vuex原理
比喻:
- 這三個(gè)由store管理,且他們的數(shù)據(jù)類型都是對(duì)象,且必須要所有組件都能看到store才行
5.2.vuex使用
5.2.1.搭建vuex環(huán)境
- 安裝vuex:
npm i vuex//vue3版本所對(duì)應(yīng)的vuex4版本
npm i vuex@3//vue2版本下載vuex3版本
-
創(chuàng)建文件:
src/store/index.js
//引入Vue核心庫 import Vue from 'vue' //引入Vuex import Vuex from 'vuex' //應(yīng)用Vuex插件 Vue.use(Vuex) //準(zhǔn)備actions對(duì)象——響應(yīng)組件中用戶的動(dòng)作 const actions = {} //準(zhǔn)備mutations對(duì)象——修改state中的數(shù)據(jù) const mutations = {} //準(zhǔn)備state對(duì)象——保存具體的數(shù)據(jù) const state = {} //創(chuàng)建并暴露store export default new Vuex.Store({ actions, mutations, state })
-
在
main.js
中創(chuàng)建vm時(shí)傳入store
配置項(xiàng)...... //引入store import store from './store' ...... //創(chuàng)建vm new Vue({ el:'#app', render: h => h(App), store })
5.2.2.基本使用
-
初始化數(shù)據(jù)、配置
actions
、配置mutations
,操作文件store.js
//引入Vue核心庫 import Vue from 'vue' //引入Vuex import Vuex from 'vuex' //引用Vuex Vue.use(Vuex) const actions = { //響應(yīng)組件中加的動(dòng)作 jia(context,value){ // console.log('actions中的jia被調(diào)用了',miniStore,value) context.commit('JIA',value) }, } const mutations = { //執(zhí)行加 JIA(state,value){ // console.log('mutations中的JIA被調(diào)用了',state,value) state.sum += value } } //初始化數(shù)據(jù) const state = { sum:0 } //創(chuàng)建并暴露store export default new Vuex.Store({ actions, mutations, state, })
-
組件中讀取vuex中的數(shù)據(jù):
$store.state.sum
-
組件中修改vuex中的數(shù)據(jù):
$store.dispatch('action中的方法名',數(shù)據(jù))
或$store.commit('mutations中的方法名',數(shù)據(jù))
備注:若沒有網(wǎng)絡(luò)請(qǐng)求或其他業(yè)務(wù)邏輯,組件中也可以越過actions,即不寫
dispatch
,直接編寫commit
html頁面中解析state時(shí)可以不加this,但js中的vue書寫時(shí)需要
5.2.3.getters的使用
-
概念:當(dāng)state中的數(shù)據(jù)需要經(jīng)過加工后再使用時(shí),可以使用getters加工。
-
在
store.js
中追加getters
配置...... const getters = { bigSum(state){ return state.sum * 10 } } //創(chuàng)建并暴露store export default new Vuex.Store({ ...... getters })
-
組件中讀取數(shù)據(jù):
$store.getters.bigSum
5.2.4.四個(gè)map方法的使用
-
mapState方法:用于幫助我們映射
state
中的數(shù)據(jù)為計(jì)算屬性computed: { //借助mapState生成計(jì)算屬性:sum、school、subject(對(duì)象寫法) ...mapState({sum:'sum',school:'school',subject:'subject'}), //借助mapState生成計(jì)算屬性:sum、school、subject(數(shù)組寫法) ...mapState(['sum','school','subject']), },
-
mapGetters方法:用于幫助我們映射
getters
中的數(shù)據(jù)為計(jì)算屬性computed: { //借助mapGetters生成計(jì)算屬性:bigSum(對(duì)象寫法) ...mapGetters({bigSum:'bigSum'}), //借助mapGetters生成計(jì)算屬性:bigSum(數(shù)組寫法) ...mapGetters(['bigSum']) },
-
mapActions方法:用于幫助我們生成與
actions
對(duì)話的方法,即:包含$store.dispatch(xxx)
的函數(shù)methods:{ //靠mapActions生成:incrementOdd、incrementWait(對(duì)象形式) ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'}) //靠mapActions生成:incrementOdd、incrementWait(數(shù)組形式) ...mapActions(['jiaOdd','jiaWait']) }
-
mapMutations方法:用于幫助我們生成與
mutations
對(duì)話的方法,即:包含$store.commit(xxx)
的函數(shù)methods:{ //靠mapActions生成:increment、decrement(對(duì)象形式) ...mapMutations({increment:'JIA',decrement:'JIAN'}), //靠mapMutations生成:JIA、JIAN(對(duì)象形式) ...mapMutations(['JIA','JIAN']), }
備注:mapActions與mapMutations使用時(shí),若需要傳遞參數(shù)需要:在模板中綁定事件時(shí)傳遞好參數(shù),否則參數(shù)是事件對(duì)象。
5.2.5.模塊化+命名空間
-
目的:讓代碼更好維護(hù),讓多種數(shù)據(jù)分類更加明確。
-
修改
store.js
const countAbout = { namespaced:true,//開啟命名空間 state:{x:1}, mutations: { ... }, actions: { ... }, getters: { bigSum(state){ return state.sum * 10 } } } const personAbout = { namespaced:true,//開啟命名空間 state:{ ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { countAbout, personAbout } })
-
開啟命名空間后,組件中讀取state數(shù)據(jù):
//方式一:自己直接讀取 this.$store.state.personAbout.list //方式二:借助mapState讀?。?/span> ...mapState('countAbout',['sum','school','subject']),
-
開啟命名空間后,組件中讀取getters數(shù)據(jù):
//方式一:自己直接讀取 this.$store.getters['personAbout/firstPersonName'] //方式二:借助mapGetters讀?。?/span> ...mapGetters('countAbout',['bigSum'])
-
開啟命名空間后,組件中調(diào)用dispatch
//方式一:自己直接dispatch this.$store.dispatch('personAbout/addPersonWang',person) //方式二:借助mapActions: ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
-
開啟命名空間后,組件中調(diào)用commit
//方式一:自己直接commit this.$store.commit('personAbout/ADD_PERSON',person) //方式二:借助mapMutations: ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
6.路由
6.1.相關(guān)理解
6.1.1.路由的理解
- 理解: 一個(gè)路由(route)就是一組映射關(guān)系(key - value),多個(gè)路由需要路由器(router)進(jìn)行管理。
- 前端路由:key是路徑,value是組件。(后端路由value是function)
6.1.2.vue-router理解
Vue的一個(gè)插件庫,專門用來實(shí)現(xiàn)SPA應(yīng)用
什么是SPA應(yīng)用:
- 單頁 Web 應(yīng)用(single page web application,SPA)
- 整個(gè)應(yīng)用只有一個(gè)完整的頁面
- 點(diǎn)擊頁面中的導(dǎo)航鏈按不會(huì)刷新頁面,只會(huì)做頁面的局部更新
- 數(shù)據(jù)需要通過ajax請(qǐng)求獲取。
6.2.基本路由
6.2.1.基本使用
-
安裝vue-router,命令:
npm i vue-router
vue2要下載npm i vue-router@3
3版本的才行 -
應(yīng)用插件:
Vue.use(VueRouter)
-
編寫router配置項(xiàng):
//引入VueRouter import VueRouter from 'vue-router' //引入Luyou 組件 import About from '../components/About' import Home from '../components/Home' //創(chuàng)建router實(shí)例對(duì)象,去管理一組一組的路由規(guī)則 const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) //暴露router export default router
-
實(shí)現(xiàn)切換(active-class可配置高亮樣式)
<router-link active-class="active" to="/about">About</router-link>
-
指定展示位置
<router-view></router-view>
6.2.2.幾個(gè)注意點(diǎn)
- 路由組件通常存放在
pages
文件夾,一般組件通常存放在components
文件夾。 - 通過切換,“隱藏”了的路由組件,默認(rèn)是被銷毀掉的,需要的時(shí)候再去掛載。
- 每個(gè)組件都有自己的
$route
屬性,里面存儲(chǔ)著自己的路由信息。 - 整個(gè)應(yīng)用只有一個(gè)router,可以通過組件的
$router
屬性獲取到。
6.3.嵌套(多級(jí))路由
-
配置路由規(guī)則,使用children配置項(xiàng):
routes:[ { path:'/about', component:About, }, { path:'/home', component:Home, children:[ //通過children配置子級(jí)路由 { path:'news', //此處一定不要寫:/news component:News }, { path:'message',//此處一定不要寫:/message component:Message } ] } ]
-
跳轉(zhuǎn)(要寫完整路徑):
<router-link to="/home/news">News</router-link>
6.4.路由的query參數(shù)
-
傳遞參數(shù)
<!-- 跳轉(zhuǎn)并攜帶query參數(shù),to的字符串寫法 --> <router-link :to="/home/message/detail?id=666&title=你好">跳轉(zhuǎn)</router-link> <!-- 跳轉(zhuǎn)并攜帶query參數(shù),to的對(duì)象寫法 --> <router-link :to="{ path:'/home/message/detail', query:{ id:666, title:'你好' } }" >跳轉(zhuǎn)</router-link>
-
接收參數(shù):
$route.query.id $route.query.title
6.5.命名路由
-
作用:可以簡(jiǎn)化路由的跳轉(zhuǎn)。
-
如何使用
-
給路由命名:
{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //給路由命名 path:'welcome', component:Hello, } ] } ] }
-
簡(jiǎn)化跳轉(zhuǎn):
<!--簡(jiǎn)化前,需要寫完整的路徑 --> <router-link to="/demo/test/welcome">跳轉(zhuǎn)</router-link> <!--簡(jiǎn)化后,直接通過名字跳轉(zhuǎn) --> <router-link :to="{name:'hello'}">跳轉(zhuǎn)</router-link> <!--簡(jiǎn)化寫法配合傳遞參數(shù) --> <router-link :to="{ name:'hello', query:{ id:666, title:'你好' } }" >跳轉(zhuǎn)</router-link>
-
6.6.路由的params參數(shù)
-
配置路由,聲明接收params參數(shù)
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符聲明接收params參數(shù) component:Detail } ] } ] }
-
傳遞參數(shù)
<!-- 跳轉(zhuǎn)并攜帶params參數(shù),to的字符串寫法 --> <router-link :to="/home/message/detail/666/你好">跳轉(zhuǎn)</router-link> <!-- 跳轉(zhuǎn)并攜帶params參數(shù),to的對(duì)象寫法 --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳轉(zhuǎn)</router-link>
特別注意:路由攜帶params參數(shù)時(shí),若使用to的對(duì)象寫法,則不能使用path配置項(xiàng),必須使用name配置!
-
接收參數(shù):
$route.params.id $route.params.title
6.7.路由的props配置
? 作用:讓路由組件更方便的收到參數(shù)
{
name:'xiangqing',
path:'detail/:id',
component:Detail,
//第一種寫法:props值為對(duì)象,該對(duì)象中所有的key-value的組合最終都會(huì)通過props傳給Detail組件
// props:{a:900}
//第二種寫法:props值為布爾值,布爾值為true,則把路由收到的所有params參數(shù)通過props傳給Detail組件
// props:true
//第三種寫法:props值為函數(shù),該函數(shù)返回的對(duì)象中每一組key-value都會(huì)通過props傳給Detail組件
props(route){
return {
id:route.query.id,
title:route.query.title
}
}
}
6.8.<router-link>的replace屬性
- 作用:控制路由跳轉(zhuǎn)時(shí)操作瀏覽器歷史記錄的模式
- 瀏覽器的歷史記錄有兩種寫入方式:分別為
push
和replace
。路由跳轉(zhuǎn)時(shí)候默認(rèn)為push
push
是追加歷史記錄replace
是替換當(dāng)前記錄 - 如何開啟
replace
模式:<router-link replace .......>News</router-link>
6.9.編程式路由導(dǎo)航
-
作用:不借助
<router-link>
實(shí)現(xiàn)路由跳轉(zhuǎn),讓路由跳轉(zhuǎn)更加靈活 -
具體編碼:
//$router的兩個(gè)API this.$router.push({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.replace({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.forward() //前進(jìn) this.$router.back() //后退 //傳數(shù)字 正數(shù)就是前進(jìn)幾步 負(fù)數(shù)就是后退幾步 this.$router.go() //可前進(jìn)也可后退
6.10.緩存路由組件
-
作用:讓不展示的路由組件保持掛載,不被銷毀。
-
具體編碼:
<!-- 緩存一個(gè)時(shí) -->
<!-- <keep-alive include="News"> --><!--緩存哪個(gè)路由<寫組件名>的內(nèi)容,不寫則都緩存-->
<!-- 緩存多個(gè)時(shí) -->
<keep-alive :include="[News, Message]">
<router-view></router-view>
</keep-alive>
6.11.兩個(gè)新的生命周期鉤子
- 作用:路由組件所獨(dú)有的兩個(gè)鉤子,用于捕獲路由組件的激活狀態(tài)。
- 具體名字:
-
activated
路由組件被激活時(shí)觸發(fā)。 -
deactivated
路由組件失活時(shí)觸發(fā)。
PS:之前講的nextTick也是一個(gè)鉤子
-
6.12.路由守衛(wèi)
-
作用:對(duì)路由進(jìn)行權(quán)限控制
-
分類:全局守衛(wèi)、獨(dú)享守衛(wèi)、組件內(nèi)守衛(wèi)
-
全局守衛(wèi):
//全局前置守衛(wèi):初始化時(shí)執(zhí)行、每次路由切換前執(zhí)行 router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from) if(to.meta.isAuth){ //判斷當(dāng)前路由是否需要進(jìn)行權(quán)限控制 if(localStorage.getItem('school') === 'atguigu'){ //權(quán)限控制的具體規(guī)則 next() //放行 }else{ alert('暫無權(quán)限查看') // next({name:'guanyu'}) } }else{ next() //放行 } }) //全局后置守衛(wèi):初始化時(shí)執(zhí)行、每次路由切換后執(zhí)行 router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //修改網(wǎng)頁的title }else{ document.title = 'vue_test' } })
-
獨(dú)享守衛(wèi):
beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ //判斷當(dāng)前路由是否需要進(jìn)行權(quán)限控制 if(localStorage.getItem('school') === 'atguigu'){ next() }else{ alert('暫無權(quán)限查看') // next({name:'guanyu'}) } }else{ next() } }
-
組件內(nèi)守衛(wèi):文章來源:http://www.zghlxwxcb.cn/news/detail-787834.html
//進(jìn)入守衛(wèi):通過路由規(guī)則,進(jìn)入該組件時(shí)被調(diào)用 beforeRouteEnter (to, from, next) { }, //離開守衛(wèi):通過路由規(guī)則,離開該組件時(shí)被調(diào)用 beforeRouteLeave (to, from, next) { }
6.13.路由器的兩種工作模式
6.13.1.hash & history
- 對(duì)于一個(gè)url來說,什么是hash值?——
#及其后面的內(nèi)容就是hash值
。 - hash值不會(huì)包含在 HTTP 請(qǐng)求中,即:hash值不會(huì)帶給服務(wù)器。
- hash模式:
- 地址中永遠(yuǎn)帶著#號(hào),不美觀 。
- 若以后將地址通過第三方手機(jī)app分享,若app校驗(yàn)嚴(yán)格,則地址會(huì)被標(biāo)記為不合法。
- 兼容性較好。
- history模式:
- 地址干凈,美觀 。
- 兼容性和hash模式相比略差。
- 應(yīng)用部署上線時(shí)需要后端人員支持,解決刷新頁面服務(wù)端404的問題。
6.13.2. nodejs部署項(xiàng)目(簡(jiǎn)單版)
nodejs部署一個(gè)項(xiàng)目的大致流程:文章來源地址http://www.zghlxwxcb.cn/news/detail-787834.html
- 打包項(xiàng)目
npm run build
注意區(qū)別是hash還是history模式 - 初始化一個(gè)項(xiàng)目
npm init
- 安裝nodejs中的express
npm i express
- 寫好server.js
(可能需要下載npm install --save connect-history-api-fallback
)
//使用nodejs部署項(xiàng)目server.js
const express = require('express')
//hash模式不用這樣
//history模式下,使用connect-history-api-fallback來解決 單獨(dú)復(fù)制并新建一個(gè)頁面填入http://localhost:5005/home/message等頁面不出現(xiàn)內(nèi)容的問題
const history = require('connect-history-api-fallback');
const app = express()
//history模式下
app.use(history())
//指定路徑
app.use(express.static(__dirname+'/static'))
/* app.get('/person',(req,res)=>{
res.send({
name:'tom',
age:18,
})
}) */
app.listen(5005,(err)=>{
if(!err) console.log('服務(wù)器啟動(dòng)成功了')
})
- 運(yùn)行項(xiàng)目
node server
7.VUE UI組件庫
7.1.移動(dòng)端常用 UI 組件庫
- Vant https://youzan.github.io/vant
- Cube UI https://didi.github.io/cube-ui
- Mint UI http://mint-ui.github.io
7.2.PC 端常用 UI 組件庫
- Element UI https://element.eleme.cn
- IView UI https://www.iviewui.co
到了這里,關(guān)于Vue(3)-vue中的Ajax、Vuex、路由及UI組件庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!