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>