我正在使用Quasar (quasar.dev)和Vue2 +组合API,并尝试访问具有动态生成的'v-bind:ref‘属性的DOM元素,遵循Vue3文档的以下页面:
https://v3.vuejs.org/guide/composition-api-template-refs.html#usage-inside-v-for
这是这个问题的代码和方框的简化表示:https://codesandbox.io/s/suspicious-pine-90qgd?file=/src/components/MyOuterComponent.ts
我的组件模板(MyOuterComponent.vue):
<template>
<div>
<my-component
v-for="(item, i) in list"
v-bind:ref="
(el) => {
if (el) divs[i] = el
}
"
v-bind:key="i"
>
{{ item }}
</my-component>
</div>
</template>
<script src='./MyOuterComponent.ts' />以及我对该组件的脚本:
import MyComponent from './MyComponent.vue'
import TMyComponent from './MyComponent'
import {
defineComponent,
onMounted,
ref,
reactive,
onBeforeUpdate
} from '@vue/composition-api'
export default defineComponent({
name: 'MyOuterComponent',
components: { MyComponent },
props: {},
setup(props, context) {
const list = reactive([1, 2, 3, 4, 5])
const divs = ref<InstanceType<typeof TMyComponent>[]>([])
// make sure to reset the refs before each update
onBeforeUpdate(() => {
divs.value = []
})
onMounted(() => {
context.root.$nextTick(() => {
console.log('THE COMPONENTs', divs, context.root.$refs)
divs.value.forEach((div) => {
console.log('My Div Ref: ', div)
})
})
})
return {
list,
divs
}
}
})正如在文档中看到的,我希望divs填充动态生成的组件的模板引用,这就是我的模板中的这一行应该做的事情:
v-bind:ref="(el) => { if (el) divs[i] = el }"即使在nextTick之后记录,divs仍为空。我希望在其中看到5个引用DOM元素的项目。
如果我将模板更改为:
<template>
<div>
<my-component
v-for="(item, i) in list"
v-bind:ref="item"
v-bind:key="i"
>
{{ item }}
</my-component>
</div>
</template>
<script src='./MyOuterComponent.ts' />我在context.refs中看到了引用,但被告知此属性将在Vue3中删除;-(
有没有人能告诉我我哪里错了?谢谢。
发布于 2021-02-03 06:52:01
看起来vue-composition-api (vue2)不支持:ref语法。看一看https://github.com/vuejs/composition-api#limitations
一个警告应该是非常有帮助的。
发布于 2021-07-30 09:12:24
首先需要导入ref:
import { ref } from "@vue/composition-api"一种简单的方法是向列表中添加一个引用。您可以使用列表索引引用所需的ref。
<template>
<div>
<my-component
ref="mycomponentRef"
v-for="(item, index) in list"
v-bind:key="index"
>
{{ item }}
</my-component>
</div>
</template>
<script>
export defineComponent({
setup() {
// this is an array, [ref0, ref1, ...]
const mycomponentRef = ref()
return { mycomponentRef }
}
})
</script>发布于 2021-11-25 14:14:45
虽然到目前为止还不支持,但您仍然可以使用旧的$refs作为变通方法。这不是在Vue3中,但在它实现之前,您会一直使用它。
<div v-for='i of 10' :key='i' ref='myRefs' />setup(props, {refs}){
// Workaround until Vue2 Composition API supports dynamic template refs.
onMounted(()=>{
myRefs = refs.myRefs // array of 10 refs
})
}https://stackoverflow.com/questions/66013172
复制相似问题