历届办法
- path+query
参数会暴露在url
- name+params
官方在2022–8-22已禁用params传参,具体看这This
- state
参数不会暴露在url,但刷新页面会失效,和以前的params一样
- store
用额外的插件来store,顾名思义存储数据,此本章不做讲解。
起手式:配置路由
无论是path还是name,都需要在路由配置中指定每个路径对应的组件。将配置都写到一个配置文件中,然后在vue的main.js中挂载配置它,具体流程是这样的:
- 首先,您需要在项目的src目录下创建一个router文件夹,用来存放路由相关的文件。
- 然后,在router文件夹中创建一个index.js文件,用来编写路由配置。例如:
language-js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| // router/index.js import { createRouter, createWebHashHistory } from 'vue-router'
// 导入路由组件 import Home from '.../components/Home.vue' import About from '.../components/About.vue'
// 定义路由 //path const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ] /* //name const routes = [ { name: "Home", path: "/", component: Home } { name: "About ", path: "/about", component: About } ]
*/ // 创建路由实例 const router = createRouter({ history: createWebHashHistory(), routes, })
// 导出路由实例 export default router
|
- 最后,在main.js文件中导入路由器对象,并将其挂载到Vue实例上。例如:
language-js
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| // main.js // 在main.js中 import { createApp } from 'vue' import App from './App.vue'
// 导入路由实例 import router from './router'
// 创建并挂载根实例 const app = createApp(App) // 使用路由实例 app.use(router) app.mount('#app')
|
1. path+query
发送方
language-typescript
1 2 3 4 5 6 7 8 9 10 11
| <script setup lang="ts"> import { useRouter } from "vue-router"; const router = useRouter(); const goPath = (id: number) => { router.push({ path: "/about", query: { id: id } }); }; </script>
|
接收方
language-typescript
1 2 3 4 5 6 7 8 9 10 11 12 13
| <script setup lang="ts"> import { useRoute } from "vue-router"; const route = useRoute(); const id = route.query.id; </script>
<template> <div>Id: { { id }}</div> </template>
|
2. state
发送方
language-typescript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <script setup lang="ts"> import { useRouter } from "vue-router"; const router = useRouter(); const goPath = (id: number) => { router.push({ path: "/about", state: { id: id } }); //或者 //router.push({ name: "About", state: { id: id } }); }; </script>
|
接收方
language-typescript
1 2 3 4 5 6 7 8 9 10
| <script setup lang="ts"> const id = history.state.data; </script>
<template> <div>Id: { { id }}</div> </template>
|
未找到相关的 Issues 进行评论
请联系 @Xiamu-ssr 初始化创建