vue 组件监听页面切换_vue项目如何监听窗口变化,达到页面自适应?
【自適應(yīng)】向來(lái)是前端工程師需要解決的一大問(wèn)題——即便作為當(dāng)今非常火熱的vue框架,也無(wú)法擺脫——雖然elementui、iview等開(kāi)源UI組件庫(kù)層出不窮,但官方庫(kù)畢竟不可能滿足全部需求,因此我們可以通過(guò)【監(jiān)聽(tīng)窗口變化】達(dá)到想要的絕大部分自適應(yīng)效果。
獲取窗口寬度:document.body.clientWidth
監(jiān)聽(tīng)窗口變化:window.onresize
同時(shí)回顧一下JS里這些方法:
網(wǎng)頁(yè)可見(jiàn)區(qū)域?qū)?#xff1a;document.body.clientWidth
網(wǎng)頁(yè)可見(jiàn)區(qū)域高:document.body.clientHeight
網(wǎng)頁(yè)可見(jiàn)區(qū)域?qū)?#xff1a;document.body.offsetWidth (包括邊線的寬)
網(wǎng)頁(yè)可見(jiàn)區(qū)域高:document.body.offsetHeight (包括邊線的寬)
我們將document.body.clientWidth賦值給data中自定義的變量:
data:{
screenWidth: document.body.clientWidth
}
在頁(yè)面mounted時(shí),掛載window.onresize方法:
mounted () {
const that = this
window.onresize = () => {
return (() => {
window.screenWidth = document.body.clientWidth
that.screenWidth = window.screenWidth
})()
}
}
監(jiān)聽(tīng)screenWidth屬性值的變化,打印并觀察screenWidth發(fā)生變化的值:
watch:{
screenWidth(val){
// 為了避免頻繁觸發(fā)resize函數(shù)導(dǎo)致頁(yè)面卡頓,使用定時(shí)器
if(!this.timer){
// 一旦監(jiān)聽(tīng)到的screenWidth值改變,就將其重新賦給data里的screenWidth
this.screenWidth = val
this.timer = true
let that = this
setTimeout(function(){
// 打印screenWidth變化的值
console.log(that.screenWidth)
that.timer = false
},400)
}
}
}
好!既然可以監(jiān)聽(tīng)到窗口screenWidth值的變化,就可以根據(jù)這個(gè)值設(shè)定不同的自適應(yīng)方案了!
【舉個(gè)例子:div或img圖片高度隨寬度自適應(yīng)】
div或img的寬度自適應(yīng)很簡(jiǎn)單——設(shè)定css里width屬性為百分比即可——但是高度呢?父級(jí)元素的高度并不是固定的(通常都是子級(jí)元素?fù)伍_(kāi)的)
如上圖,一個(gè)類似【圖片庫(kù)】的功能,當(dāng)屏幕放大縮小時(shí),我們可以設(shè)置外層邊框(也就是灰色框框)的寬度為100%,以達(dá)到自適應(yīng)——但高度無(wú)法設(shè)置,因此我們需要:
1.數(shù)據(jù)加載完后,獲取圖片(或外層框)的寬度
2.根據(jù)這個(gè)寬度,設(shè)置外層框的高度(如:寬度的60%)
3.監(jiān)聽(tīng)窗口screenWidth值的變化,每次變化都重新獲取寬度,并重新設(shè)置高度
所以,我們只需在前文代碼的基礎(chǔ)上,添加以下代碼,以確保屏幕縮放時(shí),每次監(jiān)聽(tīng)寬度變化:
mounted() {
// 1、數(shù)據(jù)首次加載完后 → 獲取圖片(或外層框)寬度,并設(shè)置其高度
this.$nextTick(() => {
// 獲取圖片(或外層框)
let imgBox = this.$refs.imgBox
// 獲取其寬度
let wImgbox = imgBox[0].getBoundingClientRect().width
// 設(shè)置其高度(以寬度的60%為例)
this.imgBox.height = 0.6 * wImgbox + 'px'
})
// 2、掛載 reisze 事件 → 屏幕縮放時(shí)監(jiān)聽(tīng)寬度變化
const that = this
window.onresize = () => {
return (() => {
// window.screenWidth = document.body.clientWidth
// that.screenWidth = window.screenWidth
// console.log(that.screenWidth)
this.$nextTick(() => {
let imgBox = this.$refs.imgBox
let wImgbox = imgBox[0].getBoundingClientRect().width
this.imgBox.height = 0.6 * wImgbox + 'px'
})
})()
}
},
最終實(shí)現(xiàn)效果如下:
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的vue 组件监听页面切换_vue项目如何监听窗口变化,达到页面自适应?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2000坐标系xy坐标几位_2000国家
- 下一篇: for vue 一行2列_JAVA基础练