如何访问 Vue.js 3 中动态引用标记的 html 元素?
How to access dynamic ref-tagged html elements in Vue.js 3?
使用 Vue.js 2 api 组合,您在 setup()
的 setupContext
参数上有一个 .ref
属性。正如许多文章和此线程中所述:https://github.com/vuejs/composition-api/issues/226 NOT 在 vue.js 3 中可用,并且您应该声明与 ref 同名的属性-ed 元素:
<div ref='name'/>
setup() {
return {
name : ref(null)
}
}
但是,如果您不知道 setup()
处的参考名称怎么办?
像这样 "minimum" 示例:
<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 or on my blog: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/
使用 Vue.js 2 api 组合,您在 setup()
的 setupContext
参数上有一个 .ref
属性。正如许多文章和此线程中所述:https://github.com/vuejs/composition-api/issues/226 NOT 在 vue.js 3 中可用,并且您应该声明与 ref 同名的属性-ed 元素:
<div ref='name'/>
setup() {
return {
name : ref(null)
}
}
但是,如果您不知道 setup()
处的参考名称怎么办?
像这样 "minimum" 示例:
<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 or on my blog: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/