使用 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/