一、安装与基础配置
安装
npm install vue-router
# 或
yarn add vue-router
引入与配置
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = new VueRouter({
mode: 'history', // 可选:hash / history
routes
})
// 挂载到 Vue 实例
new Vue({
router,
render: h => h(App)
}).$mount('#app')
二、路由基础
路由匹配规则
动态参数 :param
{ path: '/user/:id', component: User }
组件内获取参数:this.$route.params.id
嵌套路由
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile }, // 匹配 /user/profile
{ path: 'posts', component: Posts }
]
}
父组件需包含 标签。
三、导航方式
声明式导航
<router-link to="/about">About</router-link>
<!-- 动态路径 -->
<router-link :to="{ path: '/user/' + userId }">User</router-link>
<!-- 命名路由 -->
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>
编程式导航
// 跳转到指定路径
this.$router.push('/home')
// 对象形式
this.$router.push({ name: 'user', params: { id: 1 } })
// 替换当前页面(无历史记录)
this.$router.replace('/login')
// 前进/后退
this.$router.go(-1)