Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3跳转页面传递参数

作者:还依然存在   发布日期:2025-05-05   浏览:107

// 使用 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>

解释说明:

  1. 安装 Vue Router:确保你已经安装了 Vue Router,可以通过命令 npm install vue-router@4 来安装。
  2. 配置路由:在 router/index.js 中定义路由规则,其中 /detail/:id 是一个带有动态参数的路径。
  3. 引入路由:在 main.js 中引入并使用路由模块。
  4. 编程式导航:在 Home.vue 中使用 this.$router.push 方法进行页面跳转,并传递参数。
  5. 接收参数:在 Detail.vue 中通过 propsthis.$route.params 接收传递过来的参数。

这样就可以实现从一个页面跳转到另一个页面并传递参数的功能。

上一篇:vue的mixins使用

下一篇:vue3 webrtc

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站