##uniapp通过动态绑定子组件ref踩坑纪录,
入职公司4个月了刚开发完一个reac框架的后台管理的子模块后,在两周前又加入了uniapp架子开发同时兼容mpass端和微信小程序项目,最近有一个功能的实现让我很头疼,这个踩坑是它的子问题,我需要通过v-for 遍历子组件并且给子组件动态绑定ref,目的是在父组件中直接可以触发子组件的事件,但发现通过v-for 动态绑定ref有时无法拿到子组件dom,
父组件:
<template>
<view>
<view class="title" @click="switchTbs('green')">测试</view>
<swiper>
<swiper-item v-for="item in list" :key="item.color">
<my-item :color="item.color" :ref="'child'+item.color"></my-item>
</swiper-item>
</swiper>
</view>
</template>
<script>
import Item from './components/index'
export default {
data() {
return {
list: [{
color: 'red'
}, {
color: 'blue'
}, {
color: 'green'
}],
currentcolor: 'red'
}
},
components: {
'my-item': Item,
},
onLoad() {},
mounted() {
// this.$refs['red'].getList()
const ref = this.$refs['child'+this.currentcolor][0]
console.log(ref.name)
},
methods: {
switchTbs(cor) {
this.currentcolor = cor
const ref = this.$refs['child'+this.currentcolor][0]
ref.getList()
}
}
}
</script>
<style lang="scss" scoped>
.title {
width: 100vw;
height: 150px;
background-color: yellowgreen;
}
</style>
子组件
<template>
<view class="Item" :style="{backgroundColor:color}">
{{color}}
</view>
</template>
<script>
export default {
props: {
color: String
},
data() {
return {
heo: '1828',
name: 'zhangsan'
}
},
methods: {
getList() {
console.log('我是' + this.color)
}
}
}
</script>
<style lang="scss" scoped>
.Item {
height: 100vh;
width: 100%;
}
</style>