[关闭]
@Wangww0925 2019-08-07T05:47:40.000000Z 字数 1055 阅读 218

vue-cli resize监听窗口尺寸改变

vue-cli


注意事项
1、在项目中 window.onresize只能挂载一次,在多个页面中同时挂载 window.onresize时,只有其中一个 window.onresize会起作用
2、避免 window.onresize频繁挂载(待续)

例子:
1、在store.js里定义

  1. import Vue from "vue"
  2. import Vuex from "vuex"
  3. Vue.use(Vuex); // Vue.use引用
  4. // 声明常量,放置公用数据
  5. const state = {
  6. windowResizeW: document.documentElement.clientWidth,
  7. windowResizeH: document.documentElement.clientHeight
  8. }
  9. // 暴露,让外部可以引用
  10. export default new Vuex.Store({
  11. state
  12. })

2、在main.vue里挂载window.onresize

  1. <template>
  2. <div></div>
  3. </template>
  4. <script>
  5. import store from '@/store/store';
  6. export default {
  7. store, // 引用
  8. mounted : function (){
  9. let that = this;
  10. // 监听窗口尺寸改变
  11. window.onresize = function (){
  12. that.$store.state.windowResizeW = document.documentElement.clientWidth
  13. that.$store.state.windowResizeH = document.documentElement.clientHeight
  14. }
  15. }
  16. }
  17. </script>

3、在Vue页面中监听

  1. <template>
  2. <div></div>
  3. </template>
  4. <script>
  5. export default {
  6. name: '',
  7. data () {
  8. return {}
  9. },
  10. watch:{ // 监听
  11. '$store.state.windowResizeW':function(val){ //监听屏幕宽度变化
  12. console.log("屏幕宽度变化了")
  13. },
  14. '$store.state.windowResizeH':function(){ //监听屏幕高度变化
  15. console.log("屏幕高度变化了")
  16. }
  17. }
  18. }
  19. </script>

作者 wendy
2019 年 1月 3日


参考文献

resize监听窗口变化

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注