Vue 3模板引用动态名称

4
我注意到在Vue 3的组合式API <script setup>中创建模板引用时,需要使用与ref值完全相同的变量名。
例如,在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>

我想知道我是否可以像Vue 2一样使用ref,因为我的元素的ref是随机字符串,在Vue 2中只需将名称传递到$refs对象即可。

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

<script>
let myRef = this.$refs["myCustomRefName"]
</script>

但是我做不到,因为在Vue3中,我需要让变量名和ref属性值相似。感谢您提供的任何帮助。

你能解释一下你的情况吗?你可以将 ref 对象组合成一个类似于 refs 的单个对象,并通过键访问它。Refs 可以使用 ref 函数分配给您需要的任何对象。它们也可以在 getCurrentInstance() 上访问,但这不应该是第一选择。 - Estus Flask
1
@EstusFlask 我想制作一个组件库,就像这样 <Modal ref="something"/>,并且我想通过ref动态获取模态框组件。它应该像这样 $modal.open('something')。为此,我认为我需要像Vue 2一样获取refs对象。 - zuramai
检查一下 ref 函数。 - Estus Flask
@AhmadSaugi 有没有解决方案?我想构建一个错误组件,我想给它一个唯一的名称,这样我就可以从可组合中调用该特殊引用。 - Lukas
2个回答

5

这对我有用的方法是:

<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>

只需创建一个对象 refs(我之所以称其为 refs,仅是因为怀旧),并使用任何您拥有的动态名称进行调用。


4

来自ref文档的引用:

<template>
  <!-- When bound dynamically, we can define ref as a callback function, passing the element or component instance explicitly -->
  <child-component :ref="el => (child = el)"></child-component>
</template>

在上述代码中,child是一个变量,你可以随意命名 ;)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接