一、VueRouter跳轉方式
VueRouter是一個Vue.js官方提供的路由管理器。它可以通過「路由」將組件映射到URL,實現組件的切換。VueRouter提供了三種方式進行跳轉:
- 聲明式導航
- 編程式導航
- 命名路由
二、VueRouter跳轉方法
1.聲明式導航
<!--template-->
<router-link to="/home">Home</router-link>
<!--OR-->
<router-link :to="{ path: '/home' }">Home</router-link>
2.編程式導航
//HTML
<button @click="gotoHome">Home</button>
//JS
methods: {
gotoHome() {
this.$router.push('/home');
//或者
this.$router.push({ path: '/home' });
}
}
3.命名路由
<!--template-->
<router-link :to="{ name: 'home' }">Home</router-link>
//JS
const router = new VueRouter({
routes: [
{
path: '/home',
name: 'home',
component: Home
}
]
})
三、VueRouter跳轉當前頁
當你在同一個頁面中多次點擊同一個路由時,一般情況下Vue-Router不會響應。如果想進行強制跳轉,需要採用以下兩種方法之一:
- 使用$route對象的reload()方法
- 在標籤中添加:key屬性
代碼演示:
1.this.$router.go(0);//reload
2.<router-link :to="{ path:'/home',query:{id:1} }" :key="$route.fullPath">Home</router-link>
四、VueRouter跳轉原理
VueRouter是實現路由的組件,對它的理解,我們需要對Vue單文件組件有一定的了解,同時VueRouter底層是基於hash和history來實現的。下面是VueRouter的原理示意圖:
五、VueRouter跳轉之後刷新
在VueRouter中,通過路由跳轉的時候,組件是不會被銷毀的,而是被緩存起來方便下次使用。有時候我們需要組件被退出後重新渲染,這時候有兩種解決方式:
- 在$routeChange鉤子中調用組件的生命周期
- 通過在路由中添加參數,例如時間戳或隨機數,來重新渲染組件
代碼演示:
1.//JS
created() {
console.log('create');
this.init();
},
beforeDestroy() {
console.log('destroy');
},
beforeRouteEnter(to,from,next){
next(vm=>{
// 更新視圖組件
vm.$options.methods.init.call(vm);
})
},
//HTML
<!--template-->
<div>{{msg}}</div>
2.<!--template-->
<router-link :to="{path:'/home?time='+new Date().getTime()}">Home</router-link>
六、VueRouter跳轉很慢
在VueRouter中,當我們頻繁跳轉路由時,可能會出現頁面卡頓的現象。這時候可以通過使用keep-alive組件來緩存已經渲染的組件,達到提高訪問速度的目的。
<!--template-->
<keep-alive>
<router-view :key="$route.path"></router-view>
</keep-alive>
七、VueRouter官方文檔
VueRouter官網提供了詳細的中英文文檔,可以在上面查找到任何需要的信息和教程。官方文檔鏈接:VueRouter
八、VueRouter有哪些組件
VueRouter提供了三個重要的組件,分別是:
- router-link:生成一個a標籤用於跳轉到一個指定的地址。
- router-view:路由匹配到的組件將渲染在這個中。
- keep-alive:用於緩存已經渲染的組件,節約性能提高訪問速度。
九、VueRouter中文文檔
VueRouter中文文檔提供了對VueRouter實用性很強的介紹和使用方法。鏈接如下:VueRouter
十、VueRouter路由守衛
路由守衛是VueRouter中一種特殊的操作方式,可以在路由發生變化時對跳轉控制進行干預。路由守衛提供了以下三種鉤子函數:
- 全局守衛
- 組件內守衛
- 非同步路由守衛
//JS
const router = new VueRouter({
routes: [
{
path:'/home',
component: Home,
beforeEnter: (to, from, next) => {
if (localStorage.getItem('login') === 'true') {
next();
} else {
next('/login');
}
}
}
]
})
以上是VueRouter的跳轉詳解,對VueRouter的學習非常重要,在開發過程中是必須掌握的技能之一。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/153758.html