- 定义路由文件
javascript
//index.ts
import { createRouter, createWebHistory } from "vue-router";
import Dynamic from "./dynamic.vue";
const routes = [
{
path: '/p/:id',
name: 'user',
component: Dynamic
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router;
- vue app中使用
javascript
import router from 'index'
const app = createApp(mainPage)
app.use(router)
- 跳转方法
html
<template>
<router-link :to="{ name: 'user', params: { id: 'erina' } }" style='color: black;'>
User
</router-link>
<router-view :key="$route.fullPath"></router-view>
</template>
或
javascript
import { useRouter } from "vue-router";
const router = useRouter()
router.push({
name: 'user',
params: { id: 'id' }
})
说明:
- vue-router适用于SPA页面元素跳转
- router元素是复用的,
<router-view :key="$route.fullPath">
用来刷新元素