@Wangww0925
2019-08-07T05:47:40.000000Z
字数 1055
阅读 218
vue-cli
注意事项
1、在项目中 window.onresize只能挂载一次,在多个页面中同时挂载 window.onresize时,只有其中一个 window.onresize会起作用
2、避免 window.onresize频繁挂载(待续)
例子:
1、在store.js里定义
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex); // Vue.use引用
// 声明常量,放置公用数据
const state = {
windowResizeW: document.documentElement.clientWidth,
windowResizeH: document.documentElement.clientHeight
}
// 暴露,让外部可以引用
export default new Vuex.Store({
state
})
2、在main.vue里挂载window.onresize
<template>
<div></div>
</template>
<script>
import store from '@/store/store';
export default {
store, // 引用
mounted : function (){
let that = this;
// 监听窗口尺寸改变
window.onresize = function (){
that.$store.state.windowResizeW = document.documentElement.clientWidth
that.$store.state.windowResizeH = document.documentElement.clientHeight
}
}
}
</script>
3、在Vue页面中监听
<template>
<div></div>
</template>
<script>
export default {
name: '',
data () {
return {}
},
watch:{ // 监听
'$store.state.windowResizeW':function(val){ //监听屏幕宽度变化
console.log("屏幕宽度变化了")
},
'$store.state.windowResizeH':function(){ //监听屏幕高度变化
console.log("屏幕高度变化了")
}
}
}
</script>
作者 wendy
2019 年 1月 3日