浏览器可视窗口相关
开发过程中遇到一个需求,一个元素根据浏览器的高度变化,从而设置灵活高度从而实现滚动的效果。
第一步首先获取到浏览器可视窗口的高度
//在App.vue中获取浏览器可视高度
$(window).height()//代表了当前可见区域的大小,这里我们使用可视高度。js请使用 window.innerHeight
$(document).height()//则代表了整个文档的高度,可视具体情况使用。js请使用document.body.scrollHeight
第二步使用VueX将这个高度存起来,这样就不用每个页面都获取一遍了
Vuex中
const state = {
WindowHeight:'',//浏览器可视区域高度
}
const getters = {
getWindowHeight: state =>{
return state.WindowHeight
}
}
const mutations = {
saveWindowHeight(state,h){
state.WindowHeight = h
}
}
App.vue
mounted() {
this.$store.commit('saveWindowHeight',$(window).height())
//window.onresize监听浏览器窗口的改变
window.onresize =() =>{
return (()=>{
this.$store.commit('saveWindowHeight',$(window).height())
})()
}
},
第三步在子组件中使用Vuex的值
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'getWindowHeight',
]),
mapWheight() {
return this.getWindowHeight;
},
}
watch: {
mapWheight(newData) {
//this.$refs.findRightRef.style.heigh是你要控制的元素的高度
this.$refs.findRightRef.style.height = newData-(距离头部的高度)+'px';
},
}
mounted() {
//this.$refs.findRightRef.style.heigh是你要控制的元素的高度
this.$refs.findRightRef.style.height = this.getWindowHeight-(距离头部的高度)+'px';
},
end