// 使用 Vue Router 在 Vue 3 中跳转页面并传递参数的示例
// 1. 安装 Vue Router (如果还没有安装)
// npm install vue-router@4
// 2. 创建 router/index.js 文件并配置路由
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Detail from '../views/Detail.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/detail/:id', // :id 是动态参数
name: 'Detail',
component: Detail
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
// 3. 在 main.js 中引入路由
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
// 4. 在 Home.vue 中使用编程式导航跳转并传递参数
<template>
<div>
<h1>Home Page</h1>
<button @click="goToDetail">Go to Detail Page</button>
</div>
</template>
<script>
export default {
methods: {
goToDetail() {
this.$router.push({ name: 'Detail', params: { id: 123 } }) // 传递参数 id
}
}
}
</script>
// 5. 在 Detail.vue 中接收参数
<template>
<div>
<h1>Detail Page</h1>
<p>ID: {{ id }}</p>
</div>
</template>
<script>
export default {
props: ['id'], // 接收路由参数
created() {
console.log(this.$route.params.id) // 也可以通过 this.$route.params 访问参数
}
}
</script>
npm install vue-router@4
来安装。router/index.js
中定义路由规则,其中 /detail/:id
是一个带有动态参数的路径。main.js
中引入并使用路由模块。Home.vue
中使用 this.$router.push
方法进行页面跳转,并传递参数。Detail.vue
中通过 props
或 this.$route.params
接收传递过来的参数。这样就可以实现从一个页面跳转到另一个页面并传递参数的功能。
上一篇:vue的mixins使用
下一篇:vue3 webrtc
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站