// 在 main.js 设置
Vue.prototype.$isMobile = Vue.observable({ value: document.body.clientWidth < 750 })
// App.vue
export default {
name: 'App',
data() {
return {
lastResizeTimer: '',
lastResizeAt: new Date(),
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
const now = new Date()
if (now - this.lastResizeAt <= 150) return
this.lastResizeAt = now
this.$isMobile.value = document.body.clientWidth < 750
clearTimeout(this.lastResizeTimer)
this.lastResizeTimer = setTimeout(() => {
this.$isMobile.value = document.body.clientWidth < 750
}, 200)
},
},
}