vue2.0中mounted中直接获取v-for的DOM元素无效,但是mounted中使用定时器或者created中直接调用正常,原理是什么
大神好,在写代码时遇到如下问题,希望各位大神帮忙解释一下,将_calculateHeight 直接放到mounted钩子函数中获取不到想要的DOM元素,但是放置到created钩子函数中或者mounted钩子函数添加定时器后可以获取,想问一下各位大神是什么 原理。
目前我知道的知识:created:在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。 然而,挂载阶段还没开始; mounted:在挂载完成后调用;this.$nextTick中操作可以保证DOM渲染完成后在操作。按照vue的生命周期,mounted是在created之后的。
代码如下
<template>
<div class="food-wrap" ref="foodWrap">
<ul>
<li v-for="(item, indexs) in goods" :key="indexs" class="food-list food-list-hook">
<h1 class="title">{{item.name}}</h1>
<ul>
<li v-for="(food,index) in item.foods" :key="index" class="food-item border-1px">{{food.desc}}
</li>
</ul>
</li>
</ul>
</div>
</template>
<script type="text/ecmascript-6">
methods: {
created () { // 钩子函数,在实例创建之后立即调用该函数,此时el还不能使用
this.$http.get('api/goods').then(response => {
response = response.body;
if (response.errno === ERR_OK) {
this.goods = response.data;
//方法一:将_calculateHeight调用放到created钩子函数中,其中foodlist 和 this.listHeight能获取到值
this.$nextTick(() => { // 等渲染完成后在调用
this._initSrcoll();
this._calculateHeight();
});
}
});
this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee']; // 绑定class对应映射
},
mounted () { // 钩子函数,在挂载完成后调用 el指令可以使用
this.$nextTick(() => { // 等渲染完成后在调用
//方法二:将_calculateHeight函数直接放到mounted钩子函数中,其中foodlist 和 this.listHeight能获取不到值
this._calculateHeight();
this._initSrcoll();
//方法三:在mounted钩子函数中添加定时器后在调用_calculateHeight函数,其中foodlist 和 this.listHeight能获取到值
setTimeout(() => {
this._calculateHeight();
}, 20);
});
},
_initSrcoll () {
this.foodScroll = new BScroll(this.$refs.foodWrap, {probeType: 3});
this.foodScroll.on('scroll', (pos) => {
this.srcollY = Math.abs(Math.round(pos.y));
});
},
_calculateHeight () {
let height = 0;
this.listHeight.push(height);
let foodlist = this.$refs.foodWrap.getElementsByClassName('food-list-hook');
for (let i = 0; i < foodlist.length; i++) {
height += foodlist[i].clientHeight;
this.listHeight.push(height);
}
}
}
</script>