问题描述:在使用 v-for 循环页面渲染时,同时获取渲染元素是为 null。
原因:v-for 未渲染完成。
解决方法一:
- 利用 wacth+this.$nextTick 方式解决
- wacth 监听某一个 data 数据发生变化就执行方法
- nextTick: 在下次 DOM 更新循环结束之后执行回调
<template> <div v-for="(tiem,index) in test" :key="index"></div> </template> <script> export default { data(){ return{ test:[] } }, watch:{ test(){ this.$nextTick(()=>{ console.log("v-for渲染完成,可通过回调函数执行操作") }) } }, mounted(){ this.$axios({ mounteds:'get', url:'' }).then((response)=>{ this.test = response; }) } } </script>
解决方法二:
- 在回调方法中调用一次性定时器
- 利用定时器预留出页面的渲染时间,在执行方法.
<template> <div v-for="(tiem,index) in test" :key="index"></div> </template> <script> export default { data:{ return:{ test:[] } }, mounted(){ this.$axios({ mounteds:'get', url:'' }).then((response)=>{ this.test = response; this.testFun() }) }, methods:{ testFun(){ setTimeout(()=>{ console.log('预留方法调用的时间,等v-for渲染完成在执行') },2000) } } } </script>