在 vue.js 中,通过 $route 对象获取路由参数。方法包括使用 $route.params 对象、属性或在计算属性中使用。$route.params 是响应式的,当参数更改时组件会更新。
Vue.js 中获取路由参数
在 Vue.js 中,路由参数是通过 $route 对象访问的。$route 对象提供了有关当前路由的信息,包括路由参数。
如何获取路由参数
要获取路由参数,可以使用以下方法:
-
使用 $route.params 对象:
// props 接收到的路由参数 props: ['id'], data() { return { id: this.$route.params.id } }
-
使用 this.$route.params 属性:
// this 接收到的路由参数 data() { return { id: this.$route.params['id'] } }
-
在计算属性中使用 $route.params:
computed: { id() { return this.$route.params.id } }
示例
以下是一个获取路由参数的示例:
<template><div>
<h1>当前 ID:{{ id }}</h1>
</div>
</template><script>
export default {
props: ['id'],
data() {
return {
id: this.$route.params.id
}
}
}
</script>
以上组件将渲染一个带有 id 的
标签,该 id 是从路由参数中获取的。
注意:
- 路由参数是响应式的,这意味着当参数发生更改时,组件将自动更新。
- 如果路由参数不存在,$route.params 将返回一个空对象。