Vue 中屏幕改变 侧边栏显示隐藏功能
效果图
- 在缩放屏幕的时候监听到屏幕大小的变化, 侧边栏的状态跟着改变
- 代码是结合
mixin
和js
中的getBoundingClientRect()
方法 - 在页面导入
mixin
import ResizeMixin from './mixin/Resize.js'
mixins: [ResizeMixin],
getBoundingClientRect()
方法说明: 方法返回元素的大小及其相对于视口的位置。
MDN说明
mixin
代码
import store from "@/store"
const { body } = document
// 设置一个宽度的大小, 用来判断当前的侧边栏展开折叠
const WIDTH = 992
export default {
beforeMount() {
// 页面进来的时候监听 屏幕的变化 调用方法
window.addEventListener('resize', this.$_ResizeScreen)
},
beforeDestroy() {
// 页面销毁的时候移除监听 屏幕的变化 调用方法
window.removeEventListener('resize', this.$_ResizeScreen)
},
created() {
this.$_ResizeScreen()
},
methods: {
$_isMobile() {
const react = body.getBoundingClientRect()
return react.width - 1 < WIDTH
},
$_ResizeScreen() {
const side_flag = this.$_isMobile()
if (side_flag) {
store.dispatch("app/Act_flodSide")
} else if (!side_flag){
store.dispatch("app/ACT_unflodSide")
}
}
},
}
vuex
中 app.js
代码
const state = {
side_status: false, // 侧边栏状态 展开 false 或者 折叠 ture
}
const mutations = {
// 侧边栏状态 展开 或者 折叠
CHANGE_SIDESTATUS(state) {
state.side_status = !state.side_status
},
// 折叠侧边栏
FLOD_SIDE(state) {
state.side_status = true
},
// 展开侧边栏
UNFLOD_SIDE(state) {
state.side_status = false
}
}
const actions = {
// 侧边栏状态 展开 或者 折叠
change_SideStatus({ commit }) {
commit("CHANGE_SIDESTATUS")
},
// 折叠侧边栏
Act_flodSide({ commit }) {
commit("FLOD_SIDE")
},
// 展开侧边栏
ACT_unflodSide({ commit }) {
commit("UNFLOD_SIDE")
}
}
export default {
namespaced: true, // 之后在不同页面中引入getter、actions、mutations时,需要加上所属的模块名
state,
mutations,
actions
}