与 Nuxt 2 组合 API 以获取模板引用数组

Composition API with Nuxt 2 to get template refs array

我正在尝试获取不在 v-for 中的元素引用数组。我在 Nuxt 2 上使用 @nuxtjs/composition-api

(真相:我想做一个输入元素数组,这样我就可以在提交前对它们进行验证)

这在 vue 2 上听起来太简单了,因为当一个或多个组件在 html 上具有相同的引用名称时,$refs 变成了一个数组。然而,这听起来并不简单 api 并且尝试执行简单的任务让我长期陷入困境。

因此,为了处理这种情况,我创建了 1 个可组合函数。 (来源:https://v3.vuejs.org/guide/migration/array-refs.html#frontmatter-title

// file: viewRefs.js

import { onBeforeUpdate, onUpdated } from '@nuxtjs/composition-api'
export default () => {
  let itemRefs = []
  const setItemRef = el => {
    console.log('adding item ref')
    if (el) {
      itemRefs.push(el)
    }
  }
  onBeforeUpdate(() => {
    itemRefs = []
  })
  onUpdated(() => {
    console.log(itemRefs)
  })
  return {
    itemRefs,
    setItemRef
  }
}

这是我的 vue 文件:

<template>
  <div>
    <input :ref="input.setItemRef" />
    <input :ref="input.setItemRef" />
    <input :ref="input.setItemRef" />
    <input :ref="input.setItemRef" />
    <input :ref="input.setItemRef" />
    <input :ref="input.setItemRef" />
    // rest of my cool html
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  useRouter,
  ref
} from '@nuxtjs/composition-api'
import viewRefs from '~/composables/viewRefs'
export default defineComponent({
  setup() {

    const input = viewRefs()

    // awesome vue code here...
   
    return {
      input
    }
  }
})
</script>

现在当我 运行 这个文件时,我没有看到任何 adding item ref 日志。单击一个按钮,我将记录 inputitemRefs 数组中有 0 个项目。

怎么了?

Nuxt 2 基于 Vue 2,它只接受 ref attribute. The docs you linked actually refer to new behavior in Vue 3 for ref, where functions are also accepted.

的字符串

Nuxt 2 中的模板引用与它们在 Vue 2 中的组合方式相同 API:当 refv-for 中时,ref变成数组:

<template>
  <div id="app">
    <button @click="logRefs">Log refs</button>
    <input v-for="i in 4" :key="i" ref="itemRef" />
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'

export default {
  setup() {
    const itemRef = ref(null)
    return {
      itemRef,
      logRefs() {
        console.log(itemRef.value) // => array of inputs
      },
    }
  }
}
</script>

并且 setup() 不提供对 $refs 的访问,因为 template refs must be explicitly declared as reactive refs in Composition API