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



使用Vue.js 2 api组合,在setup()setupContext参数上有一个.ref属性。正如许多文章和本线程中所述:https://github.com/vuejs/composition-api/issues/226它在vue.js 3中不可用,并且应该声明与引用元素同名的属性:

<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-参考文献或在我的博客上:https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/

最新更新