Vue 3模板引用动态名称

zur*_*mai 4 vue.js vuejs3 vue-composition-api vue-script-setup

我注意到,要在 Vue 3 组合 api 中创建模板引用<script setup>,我应该创建一个与引用值完全相同的变量名称。

例如,在Vue 3 文档中:

<template>
  <div ref="root">This is a root element</div>   <--- notice the ref name "root"
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const root = ref(null)   <---- and the variable name should be "root" too

      onMounted(() => {
        console.log(root.value) 
      })

      return {
        root
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以像 Vue 2 那样使用 ref ,因为我有一些元素,其 ref 是随机字符串,并且它只需在$refs对象上传递名称即可在 Vue 2 上工作。

<div ref="myCustomRefName"></div>

<script>
let myRef = this.$refs["myCustomRefName"]
</script>
Run Code Online (Sandbox Code Playgroud)

但我不能这样做,因为在 Vue3 中,我应该相似变量名称和 ref 属性值。任何帮助将不胜感激。

小智 6

对我有用的是以下内容

<template>
  <div ref="root">This is a root element</div>   <--- notice the ref name "root"
  <div ref="foo">this is foo element</div>
  <div ref="bar">this is bar element</div>
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const refs = {
         root = ref(null), //<---- and the variable name should be "root" too
         foo = ref(null),
         bar = ref(null)
      }
      onMounted(() => {
        console.log(root.value)
        console.log(refs["root"])
      })

      return {
        ...refs
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

只需创建一个对象 refs (我将其称为 refs 只是出于怀旧之情)并使用您拥有的任何动态名称进行调用。