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: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('./views/About.vue')
}
]
const router = new VueRouter({
mode: 'history',
routes
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
声明式导航
使用 router-link 组件进行导航
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
带参数的动态路由匹配
{
path: '/user/:id',
name: 'User',
component: User
}
编程式导航
使用 router.push 方法
// 字符串路径
this.$router.push('/about')
// 带查询参数
this.$router.push({ path: '/about', query: { id: 1 } })
// 命名路由
this.$router.push({ name: 'About' })
// 带参数
this.$router.push({ name: 'User', params: { id: 123 } })
使用 router.replace 方法

this.$router.replace('/login') // 不会留下历史记录
路由传参
通过 params 传递参数
this.$router.push({ name: 'User', params: { id: 1 } })
// 在目标组件中获取
this.$route.params.id
通过 query 传递参数
this.$router.push({ path: '/user', query: { id: 1 } })
// 在目标组件中获取
this.$route.query.id
路由守卫
全局前置守卫

router.beforeEach((to, from, next) => {
// 进行权限验证等操作
next()
})
组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被验证前调用
next()
},
beforeRouteUpdate(to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
next()
}
}
路由懒加载
使用动态导入语法实现懒加载
const User = () => import('./views/User.vue')
{
path: '/user',
component: User
}
嵌套路由
配置子路由
{
path: '/user',
component: User,
children: [
{
path: 'profile',
component: Profile
},
{
path: 'settings',
component: Settings
}
]
}
在父路由组件中添加 router-view
<router-view></router-view>






