import store from '@/store'
const { body } = document
const WIDTH = 992 // refer to Bootstrap's responsive design
mounted() {
const isMobile = this.$_isMobile()
if (isMobile) {
store.dispatch('app/toggleDevice', 'mobile')
store.dispatch('app/closeSideBar', { withoutAnimation: true })
}
},
methods: { $_isMobile() { const rect = body.getBoundingClientRect() return rect.width - 1 < WIDTH },
import Cookies from 'js-cookie' const state = { device: 'desktop', } const mutations = { TOGGLE_DEVICE: (state, device) => { state.device = device } } const actions = { toggleDevice({ commit }, device) { commit('TOGGLE_DEVICE', device) }, } export default { namespaced: true, state, mutations, actions }
<template v-if="device!=='mobile'"> <search id="header-search" class="right-menu-item" /> <!-- <el-tooltip content="源碼地址" effect="dark" placement="bottom"> <hejiGit id="heji-git" class="right-menu-item hover-effect" /> </el-tooltip> <el-tooltip content="文檔地址" effect="dark" placement="bottom"> <hejiDoc id="heji-doc" class="right-menu-item hover-effect" /> </el-tooltip> --> <screenfull id="screenfull" class="right-menu-item hover-effect" /> <el-tooltip content="布局大小" effect="dark" placement="bottom"> <size-select id="size-select" class="right-menu-item hover-effect" /> </el-tooltip> </template>
computed: {
...mapGetters([
'device'
]),
getBoundingClientRect()判斷某個元素是否在可視區域
應用場景
場景:判斷某個元素是否出現了可視區域,根據是否在可視區域來執行不同動作;
/** * 判斷某個原生DOM元素是否不在屏幕可見區內 * @param {*} el 原生DOM元素 */
const isElementNotInViewport = function(el) { let rect = el.getBoundingClientRect(); return ( rect.top >= (window.innerHeight || document.documentElement.clientHeight) || rect.bottom <= 0 ); }; export { isElementNotInViewport};
isElementNotInViewport在組件內的使用:
import { isElementNotInViewport} from "@/utils/index.js"; mounted() { this.$nextTick(() => { let timer; window.addEventListener("scroll", () => { if (this.isFixed) { this.isFixed = false; } if (timer) { clearTimeout(timer); } timer = setTimeout(() => { this.handleScroll(); }, 200); }); this.handleScroll(); }); }, methods: { // 滑動出現底部按鈕 handleScroll() { if (isElementNotInViewport(this.$refs.lightBtn)) { this.isFixed = true; } else { this.isFixed = false; } }, }

getBoundingClientRect()用於獲得頁面中某個元素的左,上,右和下分別相對瀏覽器視窗的位置。
getBoundingClientRect()是DOM元素到瀏覽器可視范圍的距離(不包含文檔卷起的部分)
該函數返回一個Object對象,該對象有6個屬性:top,lef,right,bottom,width,height;