vue中实现路由跳转
vue-router 基础用法
安装 vue-router 依赖包
npm install vue-router
在 main.js 中引入并配置路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: () => import('./views/About.vue') }
]
const router = new VueRouter({
routes
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
声明式导航
使用 router-link 组件创建导航链接
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
添加 active-class 指定激活样式
<router-link to="/about" active-class="active">关于</router-link>
编程式导航
在组件方法中使用 this.$router.push
methods: {
goToAbout() {
this.$router.push('/about')
}
}
使用命名路由跳转

this.$router.push({ name: 'user', params: { userId: '123' } })
带查询参数跳转
this.$router.push({ path: 'register', query: { plan: 'private' } })
路由传参
通过 params 传递参数
// 路由配置
{ path: '/user/:id', component: User }
// 跳转方式
this.$router.push({ path: `/user/${userId}` })
通过 props 解耦
// 路由配置
{ path: '/user/:id', component: User, props: true }
// 组件接收
props: ['id']
导航守卫
全局前置守卫

router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
组件内守卫
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被确认前调用
next(vm => {
// 通过 `vm` 访问组件实例
})
}
路由懒加载
使用动态导入实现懒加载
const UserDetails = () => import('./views/UserDetails.vue')
const router = new VueRouter({
routes: [{ path: '/users/:id', component: UserDetails }]
})
嵌套路由
配置子路由
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile
}
]
}
]
在父路由组件中添加 router-view
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>






