VueJS对列表的引用



我只想将我的计时器引用到一个列表

<div class="row row-cols-2 justify-content-md-center" v-else-if="timerData.length <= 4" style="height: 100vh; background: none">
<div v-for="(t, index) in timerData" :key="t.name" class="col">
<timer 
:name="t.name"
:start="t.start"
:index="index"
ref="timers"/> // It overwrite the old component
</div>
</div>

我想这样访问:

this.$refs.timers.forEach(e => {
e.foo()
})

听起来像是在Vue 3中使用模板引用,这与Vue 2中略有不同。在Vue 3中,在v-for中使用ref需要自定义处理来收集数组中的模板引用。

首先,将数组暴露在上下文中:

// App.vue
import { ref } from 'vue'
export default {
setup() {
const timers = ref([])
return {
timers
}
}
}

然后将模板引用绑定更新为将给定元素推入数组的方法:

<timer :ref="el => timers.push(el)">

然后你可以访问这样的数组:

// App.vue
export default {
setup() {
//...
return {
callTimers() {
timers.value.forEach(t => t.foo())
}
}
}
}

演示

我认为是这样$如果要引用的实际元素上有v-for,那么refs.timers只是一个数组。请参见此处:https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-子组件实例和子元素

当ref与v-for一起使用时,您得到的ref将是一个包含镜像数据源的子组件的数组。

<div class="row row-cols-2 justify-content-md-center" v-else-if="timerData.length <= 4" style="height: 100vh; background: none">
<timer
v-for="(t, index) in timerData"
:key="t.name"
:name="t.name"
:start="t.start"
:index="index"
ref="timers"
class="col" />
</div>

最新更新