全局 使用当前页面的宽度 与 距离顶部的高度
Vuex 模块里的代码
const widths = {
namespaced: true,
state: {
currentWidths: 0,
currentTopHeights: 0
},
mutations: {
currentWidth(state) {
state.currentWidths = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
},
currentTopHeight(state) {
state.currentTopHeights = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
},
},
actions: {
resetCurrentWidth({ commit }) {
commit("currentWidth")
window.onresize = function windowResize() {
commit("currentWidth")
};
},
resetCurrentTopHeight({ state, commit }) {
window.addEventListener("scroll", () => {
commit("currentTopHeight")
})
}
},
getters: {
theCurrentWidth: function (state) {
return state.currentWidths
},
theCurrentTopHeight: function (state) {
return state.currentTopHeights
}
}
}
export default widths
使用页面
<template>
<div class="home">
宽: {{ currentWidths }}
<br>
<h1 class="title">这是 Home 页面 </h1>
<h1 class="title">这是 Home 111 </h1>
<h3 class="blues"> 高:{{ currentTopHeights }}</h3>
<h1 class="title">这是 Home 222 </h1>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
name: 'Home',
data() {
return {
};
},
methods: {
initCurrentWidth() {
this.$store.dispatch("widths/resetCurrentWidth")
},
initCurrentTopHeight() {
this.$store.dispatch("widths/resetCurrentTopHeight")
},
changeFontColor(val) {
const item = document.querySelector('.blues')
if (val >= 500) {
item.classList.add("red")
} else {
item.classList.remove('red')
}
}
},
created() {
this.initCurrentWidth()
this.initCurrentTopHeight()
},
mounted() {
},
computed: {
...mapGetters({
currentWidths: "widths/theCurrentWidth",
currentTopHeights: "widths/theCurrentTopHeight",
}),
...mapState({
})
},
watch: {
currentTopHeights: function (newVal, oldVal) {
console.log("当前距离顶部的高度", newVal)
this.changeFontColor(newVal)
}
}
};
</script>
<style scoped lang="scss">
.home {
.title {
margin: 300px;
}
}
.red {
color: red;
font-size: 36px;
}
</style>