vuejs3 - 如何在 Vue.js 3 中访问动态引用标记的 html 元素?

标签 vuejs3

使用 Vue.js 2 api-composition,你有一个 .ref setupContext 上的属性setup() 的论据.正如许多文章和此线程中所述:https://github.com/vuejs/composition-api/issues/226它会不是 在 vue.js 3 中可用,并且您应该声明与 ref-ed 元素同名的属性:

<div ref='name'/>

setup() {
  return {
    name : ref(null)
  }
}

但是,如果您不知道 setup() 处的引用名称怎么办? ?

像这个“最小”示例:
<div v-for="e in elements" @click="elements.push({name:Math.random(), content:Math.random()})">
  <div :ref="e.name">e.content</div>
</div>

setup(){
   return {
     a_function_called_later(){
       // I can use this.$refs but is there a more "vuejs3" way to do it ?
     }
     // ...???
   }
}

最佳答案

我遇到了同样的问题,并在 Vue.js Discord 中询问了它。幸运的是Carlos Rodrigues可以帮助我。

<template>
  <div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
    {{ item }}
  </div>
</template>

<script>
  import { ref, reactive, onBeforeUpdate } from 'vue'

  export default {
    setup() {
      const list = reactive([1, 2, 3])
      const divs = ref([])

      // make sure to reset the refs before each update
      onBeforeUpdate(() => {
        divs.value = []
      })

      return {
        list,
        divs
      }
    }
  }
</script>
您可以在官方文档中阅读更多相关信息:https://composition-api.vuejs.org/api.html#template-refs或在我的博客上:https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/

关于vuejs3 - 如何在 Vue.js 3 中访问动态引用标记的 html 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61155893/

相关文章:

vue.js - Uncaught TypeError : this. _map is null (Vue.js 3, Leaflet)

vue.js - Vuejs 3 中的 defineAsyncComponent

vue.js - 如何预渲染 Vue3 应用程序?

Vue.js 3 卸载和内存泄漏

vue.js - Pinia 数组更改时如何更新多个 Vue 3 组件

vuejs3 - 如何将行从一个数据表拖动到另一个数据表? (PrimeVue)

javascript - Vue 3 : Tree Menu Show

webpack - 如何修复 Vue3 Vite 在生产中丢失动态图像的问题?

typescript - 带有 Typescript 的 Vue3 -> 这个对象可能是未定义的

vue.js - 如果 Vue 3 引用是对象的属性,则它们的行为会有所不同