用vue实现界面跳转
路由配置
在Vue项目中实现界面跳转通常使用Vue Router。确保已安装Vue Router:
npm install vue-router
在src/router/index.js中配置路由:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
路由挂载
在main.js中挂载路由:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
声明式导航
在模板中使用<router-link>实现跳转:
<template>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</template>
编程式导航
在方法中使用router.push()实现跳转:
methods: {
goToAbout() {
this.$router.push('/about')
}
}
动态路由
配置带参数的路由:
const routes = [
{ path: '/user/:id', component: User }
]
跳转到动态路由:
this.$router.push('/user/123')
获取路由参数:
this.$route.params.id
路由守卫
全局前置守卫:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
// 验证逻辑
} else {
next()
}
})
组件内守卫:
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被验证前调用
next()
}
命名路由
配置命名路由:
const routes = [
{ path: '/user/:id', name: 'user', component: User }
]
通过名称跳转:
this.$router.push({ name: 'user', params: { id: 123 } })
路由传参
通过props传递参数:
const routes = [
{ path: '/user/:id', component: User, props: true }
]
在组件中接收:
props: ['id']
嵌套路由
配置嵌套路由:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile }
]
}
]
路由懒加载
实现组件懒加载:
const routes = [
{ path: '/about', component: () => import('../views/About.vue') }
]






