wordpress 上传大文件东莞seo网络公司
前言:vue2可通过ref来获取当前的dom,但是vue3有个问题,就是必须定义ref的变量名,才能使用;倘若有多个ref,一个个去定义未免过于繁琐,还有一种情况就是dom是使用v-for循环出来的,那么ref也就不确定了,无法提前定义。
解决方法1:
- 这是使用v-for循环出来的dom,ref通过index下标来命名,
<divv-for="(item, index) in dataList":key="item.id"
><mine-info:ref="el => getMineRef(el, index)":title="item.title":data="item.data"></mine-info>
</div>
- 此时mineRefList里面放的就是所有ref
const mineRefList = ref<HTMLElement[]>([]);
const getMineRef = (el:any, index:number) => {if (el) {mineRefList .value[index] = el; }
};
- 使用forEach循环去取就行,这里的 item 就是通过ref拿到的 dom元素。可以操作上面定义的变量或方法
mineRefList.value?.forEach((item: any) => {console.log(item)
});
解决方法2:
注意:与上面略相似,但是用push可能会造成ref还没渲染完得到null的情况,所以最好还是上面那样写
<divv-for="(item, index) in dataList":key="item.id"
><mine-info:ref="getMineRef":title="item.title":data="item.data"></mine-info>
</div>let mineRefList = ref<HTMLElement[]>([]);
const getMineRef = (el:any) => {if (el) {mineRefList.value.push(el);}
};mineRefList.value?.forEach((item: any) => {console.log(item)
});