晚上加点东西到列表循环里,结果发现怎么改点击事件都不生效。
查看控制台,也没有报错,只是单纯的点击不生效。
于是写了个测试按钮,一步步的挪,发现都是可以的。
一直挪到v-for中就会失效。
<div class="hot_list">
<div class="hot_info_item" v-for="(item,i) of currentImageItem.hotAreaConfigInfoList" :key="item.id">
<div class="index">{{item.sort}}</div>
<button @click="test">{{item.id}}</button>
<div class="link" @click="updateHotAreaLink">
<a v-if="item.jumpPageName">{{item.jumpPageName}}</a>
<a v-else>请选择跳转链接</a>
</div>
<div class="update" @click="updateHotAreaLink">修改</div>
<div class="delete" @click="deleteHotAreaItem(i)">删除</div>
</div>
</div>
</div>
那么问题已经定位到了,v-for的写法有什么问题吗?显然没有
控制台也没有报错,所以我只能把目光朝向了这个key身上。
这个key是我自己创建的一个dom所生成的,用作唯一标识。
进一步查看key发现,每次鼠标点击后,key值竟然发生了改变。
显然是这里的事件机制出了问题。
于是找到对应代码,有一个鼠标松开事件里确实有生成新的key,但是由于没有及时的阻止而错误的执行了。
找到了问题,对症下药即可,提前阻止即可。
const mouseupEvent = e => {
// 一个小坑,也算是个大坑。由于是dom生成的,所以id每次都是新的。
// 导致v-for的key每次点击后都是新的,无法触发任何事件也无任何报错。
if (!this.isActiveAdd) return false
if (!this.couldDrag) return false
// console.log('mouseup')
const hotAreaList = document.querySelectorAll('.hot_area_item')
// console.log('zeroPointDivList', hotAreaList)
// console.log('zeroPointDivList[0].style.width', zeroPointDivList[0].style.width)
// console.log('zeroPointDivList[0].clientWidth', zeroPointDivList[0].clientWidth)
const tempList = Array.from(hotAreaList)
// console.log('tempList', tempList)
const zeroPointDivList = tempList.filter(item => !item.clientWidth || !item.clientHeight)
const effectiveDivList = tempList.filter(item => item.clientWidth && item.clientHeight)
// 清除宽高为0的区域,优化dom结构,同时避免序号下标异常。
zeroPointDivList.forEach(e => e.remove())
const hotConfigList = effectiveDivList.map((item, i) => ({
top: item.style.top,
left: item.style.left,
width: item.style.width,
height: item.style.height,
sort: i + 1,
id: makeId('hot_area'),
jumpPageId: '',
jumpPageName: ''
}))
问题虽然解决了,但是这个报错情况也确实比较罕见,不报错,也不执行操作。
原因是就是我这里每次鼠标松开,vue中用于标记唯一标识的key就发生了改变,导致渲染和事件机制的异常。
所以key要求是唯一的,且不可变的。
很简单,但是也确实很重要!