Home > Article > Web Front-end > How to solve the problem of change events in the VUE listening window
Now I will share with you a brief discussion on the issue of VUE monitoring window change events. It has a good reference value and I hope it will be helpful to everyone.
Vuejs itself is an MVVM framework. However, when monitoring events on the window, it often seems to be insufficient.
For example, this time it was window.resize. I also searched it on Baidu before doing it. I see everyone is worried about this issue.
Question: I also encountered such a problem today, about canvas adaptation. Change the width of the canvas according to the change of the window. Note: Important issues should be mentioned three times to solve bugs in the framework. Let’s talk about the framework version first (Vue 2.x, ES6 used here)
Solution:
The first step: First define a record width as an attribute in data
data: { screenWidth: document.body.clientWidth // 这里是给到了一个默认值 (这个很重要) }
The second step : We need to talk about the method of mounting the reisze event when vue mounted
mounted () { const that = this window.onresize = function() { return function(){ window.screenWidth = document.body.clientWidth; that.screenWidth = window.screenWidth })() } }
The third step: watch to monitor the change of this attribute value, if it changes Then pass this val to this.screenWidth
watch: { screenWidth (val) { this.screenWidth = val } }
Step 4:Optimization: The page is stuck due to frequent triggering of the resize function
watch: { screenWidth (val) { if (!this.timer) { this.screenWidth = val this.timer = true let that = this setTimeout(function () { // that.screenWidth = that.$store.state.canvasWidth console.log(that.screenWidth) that.init() that.timer = false }, 400) } } }
The above is what I compiled For everyone, I hope it will be helpful to everyone in the future.
Related articles:
Vue implements tab switching plus style switching method
"==" and "===" in javaScript Detailed explanation of the difference
node.js blog project development notes
The above is the detailed content of How to solve the problem of change events in the VUE listening window. For more information, please follow other related articles on the PHP Chinese website!