vue-route 带参数的动态路由匹配
- App.veu
<script setup>
</script>
<template>
<div>
<h1>Hello App!</h1>
<!--使用 router-link 组件进行导航 -->
<!--通过传递 `to` 来指定链接 -->
<!--`<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签-->
<router-link to="/">Go to Home</router-link>
<p>---</p>
<router-link to="/about">Go to About</router-link>
<p>---</p>
<router-link to="/user/56">Go to User</router-link>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
</template>
User.veu
<template>
<div>User</div>
</template>
<script setup>
import {useRoute} from 'vue-router'
console.log(useRoute().params.id);
</script>
<!--<script>-->
<!--export default {-->
<!-- mounted(){-->
<!-- console.log(this.$router.params.id);-->
<!-- }-->
<!--}-->
<!--</script>-->
<style scoped>
</style>
main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router/index.js";
const app=createApp(App)
app.use(router)
app.mount('#app')
index.js
// 1. 定义路由组件.
// 也可以从其他文件导入
import Home from "../views/Home.vue";
import About from "../views/About.vue";
import User from "../views/User.vue";
import {createRouter, createWebHashHistory} from "vue-router";
// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/user/:id', component: User },
]
// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = createRouter({
// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
history: createWebHashHistory(),
routes, // `routes: routes` 的缩写
})
export default router
Home.vue
<template>
</template>
<script>
export default {
name: "Home"
}
</script>
<style scoped>
</style>
About.vue
<template>
</template>
<script>
export default {
name: "About"
}
</script>
<style scoped>
</style>
vue-route 404 页面
index.js
// 1. 定义路由组件.
// 也可以从其他文件导入
import Home from "../views/Home.vue";
import About from "../views/About.vue";
import User from "../views/User.vue";
import NotFound from "../views/NotFound.vue";
import {createRouter, createWebHashHistory} from "vue-router";
// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/user/:id', component: User },
{ path: '/:path(.*)', component: NotFound},//使用正则,匹配任意path
]
// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = createRouter({
// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
history: createWebHashHistory(),
routes, // `routes: routes` 的缩写
})
export default router
NotFound.vue
<template>
<h2> 404 not found </h2>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。