vue監(jiān)聽(tīng)鼠標(biāo)滾動(dòng)事件
<script>
export default {
name: "home",
data(){
return{
scrollIndex: 0, // 滾動(dòng)的當(dāng)前下標(biāo)
currentAsideIndex: 0, // 當(dāng)前側(cè)邊欄下標(biāo)
}
},
mounted () {
//監(jiān)聽(tīng)鼠標(biāo)滾動(dòng)事件,兼容chrome 随闺、ie 和 firefox
window.addEventListener('mousewheel', this.debounce(this.handleScroll,300), true)||window.addEventListener("DOMMouseScroll",this.debounce(this.handleScroll,300),false)
},
},
methods:{
// 側(cè)邊欄切換
setActiveItem (index) {
// 此處是引用elementUI的走馬燈組件實(shí)現(xiàn)列表切換
this.$refs.carousel.setActiveItem(index)
this.currentAsideIndex = index
this.scrollIndex = index
},
//函數(shù)防抖
debounce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
},
//判斷滾動(dòng)方向
handleScroll (e) {
let direction = e.deltaY > 0 ? 'down' : 'up'
if (this.scrollIndex === 0) {
direction === 'down' ? this.scrollIndex++ : this.scrollIndex = 0
} else if (this.scrollIndex === this.navList.length - 1) {
direction === 'down' ? this.scrollIndex = (this.navList.length - 1) : this.scrollIndex--
} else {
direction === 'down' ? this.scrollIndex++ : this.scrollIndex--
}
this.setActiveItem(this.scrollIndex)
}
}
</script>
vue監(jiān)聽(tīng)onresize事件
- 需求:
(1)頁(yè)面部分元素的尺寸需要根據(jù)實(shí)際打開(kāi)時(shí)瀏覽器尺寸進(jìn)行設(shè)置焙蹭;
(2)頁(yè)面打開(kāi)后冰寻,調(diào)節(jié)瀏覽器窗口大小時(shí)需要?jiǎng)討B(tài)調(diào)節(jié)部分元素的尺寸;
window.onresize只能在項(xiàng)目中一處進(jìn)行引用觸發(fā),如果在多個(gè)地方進(jìn)行引用觸發(fā)剃毒,會(huì)導(dǎo)致只有1個(gè)觸發(fā)事件生效。
解決“多個(gè)組件都需要觸發(fā)”的方案只能是通過(guò)一個(gè)地方觸發(fā)后通過(guò)組件間通信進(jìn)行觸發(fā)搂赋。
<div class="box" :style="{height:screenHeight}"></div>
data () {
return {
screenHeight: '', // 頁(yè)面內(nèi)部的動(dòng)態(tài)高度
}
},
mounted(){
// 監(jiān)聽(tīng)瀏覽器窗口縮放事件
this.screenHeight = (document.body.clientHeight - 100) + 'px'
window.onresize = () => {
return (() => {
this.screenHeight = (document.body.clientHeight - 100) + 'px'
})()
}
}