// 在 Vue 中获取路径参数通常使用 vue-router。以下是一个简单的示例,展示了如何获取路径参数。
// 1. 首先确保你已经安装并配置了 vue-router。
// 2. 定义路由时使用动态路径参数,例如 :id 表示一个动态参数。
const routes = [
{
path: '/user/:id',
component: User
}
]
// 3. 在组件中通过 this.$route.params 访问路径参数。
<template>
<div>
<p>User ID: {{ userId }}</p>
</div>
</template>
<script>
export default {
data() {
return {
userId: null
}
},
created() {
// 获取路径中的 id 参数
this.userId = this.$route.params.id;
},
watch: {
// 监听 $route 变化,以便在用户导航到不同参数的同一路径时更新数据
'$route' (to, from) {
this.userId = to.params.id;
}
}
}
</script>
// 解释说明:
// - `this.$route.params` 用于访问当前路由的路径参数。
// - 使用 `watch` 监听 `$route` 变化,可以在用户导航到相同路径但参数不同的情况下更新组件数据。
下一篇:vue3 clipboard
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站