1. store中初始化相关变量
const getDefaultState = () => {
return {
winSizeData: {
width: 0,
height: 0
}
};
};
const mutations = {
SET_WINSIZE_DATA: (state, data) => {
state.winSizeData = data;
}
};
const actions = {
setWinSizeData({ commit }, data) {
commit('SET_WINSIZE_DATA', data);
}
};
export default {
namespaced: true,
state,
mutations,
actions
};
2. 动态监听
在根节点App.vue监听
import { mapActions } from 'vuex';
export default {
data() {
return {
resizeEvt: null,
recalc: null
}
},
mounted() {
const { setWinSizeData } = this;
var docEl = document.documentElement;
this.resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'onResize';
this.recalc = function() {
var clientWidth = docEl.clientWidth;
var clientHeight = docEl.clientHeight;
if (!clientWidth) return;
if (!clientHeight) return;
setWinSizeData({
width: clientWidth,
height: clientHeight
});
};
window.onresize = () => {
this.recalc();
};
this.recalc();
},
beforeDestroy() {
this.recalc = () => {};
},
methods: {
...mapActions({
setWinSizeData: 'app/setWinSizeData'
})
}
}
3. 实际项目中使用该数据
<template>
<div class="wrapper"
:style="{ 'transform': `scale(${winSizeData.width/1920}, ${winSizeData.height/1080})` }">
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['winSizeData'])
}
}
</script>
<style lang="scss" scoped>
.wrapper {
width: 1920px;
height: 1080px;
}
</style>
注意: 缩放的控件一定要设置宽高