基础用法:
//app.vue
<router-link to="/">go home</router-link>
<router-link to="/about">go about</router-link>
//index.js
import home from "../components/home.vue"
import about from "../components/about.vue"
import {createWebHashHistory, createRouter} from "vue-router" //无需导入VueRouter,直接导入方法
const routes = [
{
path:'/',
component:home //注意component不是components,万恶的代码补全
},
{
path: '/about',
component: about
}
]
const router = createRouter({
history:createWebHashHistory(),
routes
})
export default router
//main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from "@/router/index.js";
createApp(App).use(router).mount('#app') //从index.js导入router后 app.use(router)
动态匹配(传递路由参数):
//user组件
<h1>这是{{ $route.params.id }}</h1>
//index.js
{
path: '/user/:id', //:id作为形参部分
component: user
}
//app.vue
<router-link to="/user/12">12user</router-link>
<router-link to="/user/13">13user</router-link> //向user组件传递参数
路由匹配语法:
path: '/user/:id(\\d+)' ID后加 (\\d+)表限定id为数字
ID后加 (\\d+)*表id可为数字也可为数组
---如<router-link to="/user/12/13/14/15">12user</router-link>
ID后加 (\\d+)?表id可有可无
子路由(嵌套路由):
//user.vue
<router-link to="/user/:id/UserPosts">头像</router-link>
<router-link to="/user/:id/UserProfile">岗位</router-link>
<router-view></router-view> //在父组件中添加子组件的路由跳转和路由出口
//index.js
{
path: '/user/:id',
component: user,
children:[
{
path:'/user/:id/UserPosts',
component:UserPosts
},
{
path: '/user/:id/UserProfile',
component: UserProfile
}
]
} //在父路由中用children标签定义子路由
命名路由:
//index.js
{
path: '/user/:id',
name:'user', //name为路由命名
component: user,
children:[
{
path:'/user/:id/UserPosts',
component:UserPosts
},
{
path: '/user/:id/UserProfile',
component: UserProfile
}
]
}
//app.vue
<router-link :to="{name:'user',params:{id:'12'}}">12user</router-link>
<router-link :to="{name:'user',params:{id:'13'}}">13user</router-link>
//:to用以绑定对象,params传递参数
路由视图:
//index.js
{
path:'/',
name:'home',
components:{ //改component为components,传入默认组件匹配未命名路由出口,具名组件匹配命名视图
default:home,
test2:about
},
},
//app.vue
<router-view></router-view>
<br><br>
<router-view name="test2"></router-view>
编程式导航:
router.push({name:'home',params:{id:''}}) //以对象形式传递参数
重定向:
{
path: '/',
redirect:{ //输入'/'后默认向about组件跳转
name:'about'
}
},
路由组件传参:
//index.js
path: '/user/:id',
name:'user',
props:true,
component: user,