如何获取vue 3中路由器的参数?

anauzrmj  于 2023-03-13  发布在  Vue.js
关注(0)|答案(3)|浏览(157)

我在Vue.js 3和TypeScript中创建了一个项目。
router.js

{
    path: "/app/:id",
    name: "Detail",
    component: Detail,
    props: true
  },

App.js

<script lang="ts">

...

onMounted(() => {
      const id = $route.params.id;
      ...
    });

但这会导致错误:

"Cannot find name '$route'."

我哪里做错了?

exdqitrt

exdqitrt1#

Vue路由器4.x为此提供useRoute()

import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()

    onMounted(() => {
      const id = route.params.id
    })
  }
}

demo

0h4hbjxa

0h4hbjxa2#

如果我们使用最新的Vue 3“脚本设置”SFC方式,则

<script setup>
import { useRoute } from 'vue-router';

const route = useRoute();  
const id = route.params.id; // read parameter id (it is reactive) 

</script>
lqfhib0f

lqfhib0f3#

您还可以使用组合API来编写自己的组合,当param为数组时,该组合提供更好的语法和优雅的处理。

const id = useRouteParam('id')

组成

import { computed, Ref } from 'vue'
import { useRoute } from 'vue-router'

export function useRouteParam(param: string, useFirstIfArray?: true): Ref<string>
export function useRouteParam(param: string, useFirstIfArray: false): Ref<string | string[]>
export function useRouteParam(param: string, useFirstIfArray = true): Ref<string | string[]> {
  const route = useRoute()

  return computed(() => {
    let paramValue = route.params[param]

    if (useFirstIfArray && Array.isArray(paramValue) && paramValue.length) {
      [paramValue] = paramValue
    }

    return paramValue
  })
}

https://github.com/PrefectHQ/vue-compositions/tree/main/src/useRouteParam

相关问题