vue项目经验:window.onresize的使用

重点window.onresize只能在一个组件中使用,如果多个组件调用则会出现覆盖情况,所以我的解决方案是在App.vue中使用,获取document.documentElement.clientWidth(即浏览器宽度)存放在vuex中,别的组件只需要用computed(计算属性)将vuex的clientWidth获取,然后通过watch监听clientWidth的值,即可触发组件事件

App.vue代码

<script>
export default {
  name: 'app',
  mounted () {
    window.onresize = () => {
      this.clientWidthResize()
    }
  },
  methods: {
    clientWidthResize () {
      this.$store.commit('Tool/resizeWidth', Number(document.documentElement.clientWidth))
    }
  }
}
</script>

store中tool.js代码(此处进行模块化开发)

export default {
  namespaced: true,
  state: {
    clientWidth: 0
  },
  getters: {},
  mutations: {
    resizeWidth(state, clientWidth) {
      state.clientWidth = clientWidth;
    },
  },
  actions: {},
}

组件使用

computed: {
  clientWidth () {
    return this.$store.state.Tool.clientWidth || Number(document.documentElement.clientWidth)
  }
},
watch: {
  clientWidth (val) {
    console.log(val)
  }
},
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值