简体   繁体   English

如何在Vue3中获取Ref数组的属性值

[英]How to get property value of a Ref's array in Vue3

I'm using a ref to define the values of a select element in a Vue3 app like this, and binding it to another ref.我正在使用 ref 在这样的 Vue3 应用程序中定义 select 元素的值,并将其绑定到另一个 ref。

<v-select
      v-model="selectedLevels"
      :items="levels"
      multiple
      label="Levels"
    ></v-select>

... 
const selectedLevels = ref([])

const levels = ref([
    { title: 'Level 1', value: 1 },
    { title: 'Level 2', value: 2 },
    { title: 'Level 3', value: 3 },
    { title: 'Level 4', value: 4 }
  ])

The selection is passed to a function to call the API, apending the level selected as a query parameter.选择被传递给 function 以调用 API,附加选择的级别作为查询参数。

export function useCategoriesQuery(
  {
    page = 1,
    levels = [1, 2, 3]
  }: { page?: Ref<number> | number; levels?: Ref<number[]> | number[] },
  { enabled }: { enabled: ComputedRef<boolean> | boolean } = { enabled: true }
) {
  return useQuery(
    ['categories', { page, levels }],
    () =>
      axios.get<{ data: ICategory[] }>(`/products/categories/`, {
        params: {
          page: page instanceof Object ? page.value : page,
          levels: Array.isArray(levels) ? levels : levels.value
        }
      }),
    {
      enabled,
      select: (response) =>
        response.data.data
          .map((dataDto) => new Category(dataDto))
          .sort((a, b) => (a.order > b.order ? 1 : -1))
    }
  )
}

I use this function useCategoryQuery in another views of the application without problem.我在应用程序的另一个视图中使用这个 function useCategoryQuery没有问题。 Normally the level variable, as you can see in the type definition, is either a number or an array of numbers, level=1 or level=1,2,3 for example.通常, level变量,如您在类型定义中所见,是一个数字或数字数组,例如level=1level=1,2,3

The problem, as you can imagine, is that the ref variable is not an Array or a number, it's a ref object (type never because it's not defined).正如您可以想象的那样,问题在于 ref 变量不是数组或数字,而是 ref object (类型 never 因为它没有定义)。 I tried to map the values, but without success.我尝试了 map 的值,但没有成功。 I always get a "levels.map is not a function" or "levels.value.map undefined".我总是得到“levels.map 不是函数”或“levels.value.map 未定义”。

Tried:试过:

if (levels instanceof Object) {
  selection = levels.value.map(level => level.value)
}

This works in the view before passing as parameter, but only when I have 1 item selected (note that multiple is enabled)这在作为参数传递之前在视图中有效,但仅当我选择了 1 个项目时(请注意启用了多个)

 Object.values(levels)

How I can get the value prop of the selected items of the Ref?如何获取 Ref 所选项目的 value 道具?

Have you tried你有没有尝试过

if (levels.value instanceof Object) {
  selection = levels.value.map(level => level.value)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM