vue3之带参数的动态路由

在应用中,可以使用<router-link> 内置组件或 $router.push 方法来导航到带参数的路由。

定义路由

// 引入 Vue 和 Vue Router  
import { createRouter, createWebHistory } from 'vue-router';  
  
// 引入组件  
import Home from '../views/Home.vue';  
import User from '../views/User.vue';  
  
const routes = [  
  {  
    path: '/',  
    name: 'Home',  
    component: Home  
  },  
  {  
    path: '/user/:id', // 这里是带参数的动态路由  
    name: 'User',  
    component: User  
  }  
];  
  
const router = createRouter({  
  history: createWebHistory(),  
  routes  
});  
  
export default router;

在组件中使用参数

/*******************************************************************************/
你可以通过 $route.params 来访问路由参数。
<template>  
  <div>  
    <h1>User Info</h1>  
    <p>User ID: {{ $route.params.id }}</p>  
    <!-- 在这里可以根据 $route.params.id 来获取和展示用户信息 -->  
  </div>  
</template>  
  
<script>  
export default {  
  name: 'User',  
  mounted() {  
    // 在组件挂载后,你可以通过 $route.params.id 来获取参数并执行相关操作  
    const userId = this.$route.params.id;  
    // TODO: 根据 userId 获取用户信息并展示  
  }  
}  
</script>

导航到带参数的路由

/*******************************使用 <router-link> 组件:************************************************/
<template>  
  <div>  
    <router-link :to="`/user/${userId}`">Go to User</router-link>  
  </div>  
</template>  
  
<script>  
export default {  
  data() {  
    return {  
      userId: 123 // 假设这是你要导航到的用户ID  
    };  
  }  
}  
/*******************************使用 router.push 方法:************************************************/
// 假设 this 是 Vue 组件的实例,userId 是你要导航到的用户ID
this.$router.push(`/user/${userId}`); 
</script>

相关推荐

  1. vue3参数动态

    2024-03-17 07:44:05       45 阅读
  2. vue3动态

    2024-03-17 07:44:05       35 阅读
  3. vue3 + ts,如何获取传递参数

    2024-03-17 07:44:05       40 阅读
  4. vue3+vite动态实现方式

    2024-03-17 07:44:05       66 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-17 07:44:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-17 07:44:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-17 07:44:05       82 阅读
  4. Python语言-面向对象

    2024-03-17 07:44:05       91 阅读

热门阅读

  1. Flutter中GetX的用法(路由管理)

    2024-03-17 07:44:05       36 阅读
  2. Flutter 的 switch 语句补遗

    2024-03-17 07:44:05       41 阅读
  3. ctf-web23

    ctf-web23

    2024-03-17 07:44:05      43 阅读
  4. SDN网络简单认识(2)——南向接口

    2024-03-17 07:44:05       37 阅读
  5. LeetCode 222.完全二叉树的节点个数

    2024-03-17 07:44:05       45 阅读
  6. MATLAB中的数据类型,例如double,char,logical等。

    2024-03-17 07:44:05       46 阅读
  7. Android什么情况下会出现内存泄漏以及怎么解决?

    2024-03-17 07:44:05       46 阅读