vue手寫<RouterLink/>組件實現(xiàn)demo詳解
手寫<RouterLink/>組件
上一節(jié) 手寫<RouterView/>組件
如果使用a標(biāo)簽
改變頁面會重新發(fā)起請求,但是我們點擊<RouterLink/>
的時候不會。以下手把手實現(xiàn)一個簡單的<RouterLink/>
組件。這節(jié)內(nèi)容與手寫<RouterView/>
組件(上一節(jié)內(nèi)容)有一定的聯(lián)系,建議先看一下。
1、加上一個響應(yīng)式數(shù)據(jù)
在上一節(jié)的基礎(chǔ)上加上一個響應(yīng)式數(shù)據(jù)(把獲取當(dāng)前路徑寫在了這里)。
import?About?from?'../view/About.vue' import?Home?from?'../view/Home.vue' import?{ref}?from?'vue' export?default?[ ????{ ????????path:?'/', ????????component:?Home ????}, ????{ ????????path:?'/about', ????????component:?About ????} ] //?新加內(nèi)容 export?const?path?=?ref(window.location.pathname)
2、對<RouterView/>組件進行簡單的改造
<template> ????<div> ????????<component?:is="view"></component> ????</div> </template> <script?setup> import?{?computed?}?from?'vue' import?Router?from?'../Router'; //?引入path這個響應(yīng)式數(shù)據(jù) import?{?path?}?from?'../Router'; const?view?=?computed(()?=>?{ ??//?這里直接使用的path ???const?res?=?Router.find(item?=>?item.path?==?path.value) ???return?res.component }) </script> <style?lang="scss"?scoped> </style>
3、創(chuàng)建<RouterLink/>組件
內(nèi)容如下:
@click.prevent
阻止a
標(biāo)簽的默認(rèn)行為,讓其被點擊時執(zhí)行push
函數(shù)。push
函數(shù)里執(zhí)行的就是改變path
為要加載的頁面路徑。
<template> ????<div> ????????<a?:href="to" rel="external nofollow" ?@click.prevent="push"> ????????????<slot></slot> ????????</a> ????</div> </template> <script?setup> import?{?path?}?from?'../Router'; const?props?=?defineProps({ ????to:?{type:?String,?required:?true} }) const?push?=?()?=>?{ ????path.value?=?props.to } </script>
4、在App.vue中使用
當(dāng)你點擊時不會重新請求。
<RouterLink?:to="'/'">首頁</RouterLink> <RouterLink?:to="'/about'">關(guān)于</RouterLink> <RouterView></RouterView>
以上就是vue手寫RouterLink組件實現(xiàn)demo詳解的詳細(xì)內(nèi)容,更多關(guān)于vue手寫RouterLink組件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue3使用pdf.js來預(yù)覽文件的操作步驟(本地文件測試)
這篇文章主要介紹了vue3使用pdf.js來預(yù)覽文件的操作步驟(本地文件測試),文中通過代碼示例和圖文結(jié)合的方式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-05-05Vue中的數(shù)據(jù)監(jiān)聽和數(shù)據(jù)交互案例解析
這篇文章主要介紹了Vue中的數(shù)據(jù)監(jiān)聽和數(shù)據(jù)交互案例解析,在文章開頭部分先給大家介紹了vue中的數(shù)據(jù)監(jiān)聽事件$watch,具體代碼講解,大家可以參考下本文2017-07-07vue.js+elementUI實現(xiàn)點擊左右箭頭切換頭像功能(類似輪播圖效果)
這篇文章主要介紹了vue.js+elementUI實現(xiàn)點擊左右箭頭切換頭像功能(類似輪播圖),本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09Electron采集桌面共享和系統(tǒng)音頻(桌面捕獲)實例
這篇文章主要為大家介紹了Electron采集桌面共享和系統(tǒng)音頻(桌面捕獲)實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10