前面几天稍微懂Vue能做到哪些是情,今天就要来深入了解Vue的生命周期,看他怎麽从无到有来处理我们对他下的指令。
scrollHeight
和realScrollHeight
起始值是一样的,但在更新内容之後会变得不等高,这是因为更新时采非同步执行,侦测到资料更新时Vue会开启一个队列,让更新的资料暂时放在里面,直到下个事件循环(tick),才会把暂放的资料渲染到实际的DOM上面。
在for回圈中,连续更改了1000次 number 的资料,如果使用同步更新,则需要1000次更新。但用nextTick()可以在跑完回圈後,做一次性更新,这样可以减少资料重复更新与不必要的计算。—-Vue nextTick 处理完成後就换我!
为了要让他资料同步,可以使用$nextTick
,异步更新队列,使updated
阶段中的资料全部都可以再次被渲染。
<div class="box">
<div v-for="item in messages">{{item}}</div>
</div>
<input type="text" v-model="msg" @keydown.enter="addToMsg">
<p>
msg:{{messages}}<br>
scrollHeight: {{ scrollHeight }} <br>
DOM 实际的 scrollHeight: {{ realScrollHeight }}
</p>
const vm = Vue.createApp({
data: function () {
return {
msg: '',
messages: ['A', 'SE', 'XYZ'],
scrollHeight: 0,
realScrollHeight: 0
}
},
methods: {
addToMsg: function () {
this.messages.push(this.msg)
this.msg = ''
const el = document.querySelector('.box');
this.scrollHeight = el.scrollHeight;//新增内容後更新scrollHeight
el.scrollTop = el.scrollHeight;//滚轴滚动到底部
this.$nextTick(() => {
const el = document.querySelector('.box');
this.scrollHeight = el.scrollHeight;
el.scrollTop = el.scrollHeight;
this.realScrollHeight = el.scrollHeight;
});
}
},
mounted() {
const el = document.querySelector('.box');
this.realScrollHeight = el.scrollHeight;
this.scrollHeight = el.scrollHeight;
}
}).mount('#app');
生命周期
https://www.daimajiaoliu.com/daima/476117bdf900403
https://ithelp.ithome.com.tw/articles/10217199
Vue.js异步更新及nextTick
https://codertw.com/程序语言/646446/
图解Vue异步更新原理
https://segmentfault.com/a/1190000023649590
Vue nextTick 处理完成後就换我!
https://ithelp.ithome.com.tw/articles/10240669
<<: [Day 08] tinyML开胃菜Arduino IDE上桌(上)
>>: Python 演算法 Day 9 - Exploratory Data Analysis
参赛动机 原本是职缺是应徵网页前端工程师,因为公司目前需要有人帮忙写 App ,就被推坑一起写 Fl...
参考页面: https://www.tensorflow.org/text/tutorials/cl...
第二天我来说一下如何做1块属於自己的开发板,分享我在做STM32的开发板经验,我不会说我的做法是最好...
前言: 昨天介绍完进入时的渐入效果,今天会继续将剩下的范例介绍完 并在最後会介绍自定义前缀词 范例:...
某天闲晃网站时看到一个充满魔性的选单按钮 是这个样子的 图源:https://www.pintere...