【问题标题】:Set reactive screen width with vuejs使用 vuejs 设置响应式屏幕宽度
【发布时间】:2019-01-05 00:19:56
【问题描述】:
是否可以在变量或数据属性跟踪窗口调整大小的情况下具有反应式窗口宽度
例如
computed:{
smallScreen(){
if(window.innerWidth < 720){
this.$set(this.screen_size, "width", window.innerWidth)
return true
}
return false
}
【问题讨论】:
标签:
vue.js
window
width
screen
reactive-programming
【解决方案1】:
除非您在窗口上附加一个侦听器,否则我认为没有办法做到这一点。
您可以在组件的data 上添加属性windowWidth 并附加在安装组件时修改值的resize 侦听器。
试试这样的:
<template>
<p>Resize me! Current width is: {{ windowWidth }}</p>
</template
<script>
export default {
data() {
return {
windowWidth: window.innerWidth
}
},
mounted() {
window.onresize = () => {
this.windowWidth = window.innerWidth
}
}
}
</script>
希望有帮助!
【解决方案2】:
你还可以根据窗口宽度附加一个类
<template>
<p :class="[`${windowWidth > 769 && windowWidth <= 1024 ? 'special__class':'normal__class'}`]">Resize me! Current width is: {{ windowWidth }}</p>
</template>
<script>
export default {
data() {
return {
windowWidth: window.innerWidth
}
},
mounted() {
window.onresize = () => {
this.windowWidth = window.innerWidth
}
}
}
</script>
<style scoped>
.normal__class{
}
.special__class{
}
</style>
【解决方案3】:
如果您在此解决方案中使用多个组件,则接受的答案的调整大小处理函数将仅更新最后一个组件。
那么你应该改用这个:
import { Component, Vue } from 'vue-property-decorator';
@Component
export class WidthWatcher extends Vue {
public windowWidth: number = window.innerWidth;
public mounted() {
window.addEventListener('resize', this.handleResize);
}
public handleResize() {
this.windowWidth = window.innerWidth;
}
public beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}
}
来源:https://github.com/vuejs/vue/issues/1915#issuecomment-159334432