vue手寫<RouterLink/>組件實現(xiàn)demo詳解
手寫<RouterLink/>組件
上一節(jié) 手寫<RouterView/>組件
如果使用a標簽改變頁面會重新發(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ù)(把獲取當前路徑寫在了這里)。
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標簽的默認行為,讓其被點擊時執(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中使用
當你點擊時不會重新請求。
<RouterLink?:to="'/'">首頁</RouterLink> <RouterLink?:to="'/about'">關(guān)于</RouterLink> <RouterView></RouterView>
以上就是vue手寫RouterLink組件實現(xiàn)demo詳解的詳細內(nèi)容,更多關(guān)于vue手寫RouterLink組件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決vue中監(jiān)聽input只能輸入數(shù)字及英文或者其他情況的問題
今天小編就為大家分享一篇解決vue中監(jiān)聽input只能輸入數(shù)字及英文或者其他情況的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Vue API中setup ref reactive函數(shù)使用教程
setup是用來寫組合式api,內(nèi)部的數(shù)據(jù)和方法需要通過return之后,模板才能使用。在之前vue2中,data返回的數(shù)據(jù),可以直接進行雙向綁定使用,如果我們把setup中數(shù)據(jù)類型直接雙向綁定,發(fā)現(xiàn)變量并不能實時響應(yīng)。接下來就詳細看看它們的使用2022-12-12

