vue 实现跳转
路由跳转实现
在Vue中实现页面跳转通常使用Vue Router,这是Vue.js官方的路由管理器。它和Vue.js核心深度集成,使构建单页面应用变得易如反掌。
安装Vue Router:
npm install vue-router
配置基本路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = new VueRouter({
routes
})
export default router
声明式导航
使用<router-link>组件创建导航链接:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
可以添加active-class属性自定义激活状态的类名:
<router-link to="/about" active-class="active-link">About</router-link>
编程式导航
通过this.$router.push()方法实现编程式导航:
methods: {
goToAbout() {
this.$router.push('/about')
}
}
带参数的跳转:
this.$router.push({ path: '/user', query: { id: '123' } })
// 或
this.$router.push({ name: 'user', params: { id: '123' } })
命名路由
在路由配置中给路由设置名称:
const routes = [
{
path: '/user/:id',
name: 'user',
component: User
}
]
使用命名路由跳转:
this.$router.push({ name: 'user', params: { id: '123' } })
路由传参
通过params传递参数:
this.$router.push({ name: 'user', params: { userId: '123' } })
在目标组件中接收参数:
this.$route.params.userId
通过query传递参数:
this.$router.push({ path: '/user', query: { id: '123' } })
在目标组件中接收query参数:
this.$route.query.id
路由守卫
全局前置守卫:

router.beforeEach((to, from, next) => {
// 必须调用next()
})
路由独享守卫:
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 守卫逻辑
}
}
]
组件内守卫:
export default {
beforeRouteEnter(to, from, next) {
// 不能访问this
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变但组件被复用时调用
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件时调用
}
}
动态路由匹配
使用冒号标记动态路径参数:
const routes = [
{ path: '/user/:id', component: User }
]
在组件中访问参数:
this.$route.params.id
响应路由参数变化:
watch: {
'$route'(to, from) {
// 对路由变化作出响应
}
}
路由模式
hash模式(默认):
const router = new VueRouter({
mode: 'hash',
routes
})
history模式(需要服务器配置支持):

const router = new VueRouter({
mode: 'history',
routes
})
路由懒加载
使用动态导入实现路由懒加载:
const routes = [
{
path: '/about',
component: () => import('./views/About.vue')
}
]
嵌套路由
定义嵌套路由:
const routes = [
{
path: '/user',
component: User,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
]
在父路由组件中添加<router-view>:
<div class="user">
<router-view></router-view>
</div>
路由重定向和别名
重定向:
const routes = [
{ path: '/home', redirect: '/' }
]
命名重定向:
const routes = [
{ path: '/home', redirect: { name: 'homepage' } }
]
路由别名:
const routes = [
{ path: '/', component: Home, alias: '/home' }
]
导航守卫中的元字段
定义路由元信息:
const routes = [
{
path: '/admin',
meta: { requiresAuth: true }
}
]
在守卫中使用:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// 需要认证
}
})






