在我使用Vue的移动网络应用程序中,我想在软键盘弹出时隐藏我的页脚.所以我有一点功能来测试窗口高度与窗口宽度的比例......
showFooter(){
return h / w > 1.2 || h > 560;
}
Run Code Online (Sandbox Code Playgroud)
...我在我的数据中声明了window.innerHeight/window.innerWidth.
data: { h: window.innerHeight, w: window.innerWidth }
Run Code Online (Sandbox Code Playgroud)
麻烦的是,当window.innerHeight改变时,我的h属性不会获得新值.我该怎么看window.innerHeight?
sam*_*ayo 28
我相信有更好的方法可以做到这一点,但是这个会对你有用,直到我想出一些东西:
基本上你只需要一个数据道具和一个观察者就可以做到这一点.
new Vue({
el: '#app',
data() {
return {
windowHeight: 0,
txt: ''
}
},
watch: {
windowHeight(newHeight, oldHeight) {
this.txt = `it changed to ${newHeight} from ${oldHeight}`;
}
},
mounted() {
this.$nextTick(() => {
window.addEventListener('resize', () => {
this.windowHeight = window.innerHeight
});
})
},
});
Run Code Online (Sandbox Code Playgroud)
这将输出jsfiddle示例的更改
<div id="app">
<br> Window height: {{ windowHeight }} <br/>
{{ txt }}
</div>
Run Code Online (Sandbox Code Playgroud)
ksh*_*drt 19
3
在 Vue 3 中,您可以创建一个组合函数,该函数可以返回反应宽度和断点名称值。您可以轻松地跨多个组件重用该函数 (useBreakpoints.js)。
import { computed, onMounted, onUnmounted, ref } from "vue"
export default function () {
let windowWidth = ref(window.innerWidth)
const onWidthChange = () => windowWidth.value = window.innerWidth
onMounted(() => window.addEventListener('resize', onWidthChange))
onUnmounted(() => window.removeEventListener('resize', onWidthChange))
const type = computed(() => {
if (windowWidth.value < 550) return 'xs'
if (windowWidth.value > 549 && windowWidth.value < 1200) return 'md'
if (windowWidth.value > 1199) return 'lg'
})
const width = computed(() => windowWidth.value)
return { width, type }
}
Run Code Online (Sandbox Code Playgroud)
您可以在 vue 3 组件的设置方法中使用它,如下所示。
const { width, type } = useBreakpoints()
Run Code Online (Sandbox Code Playgroud)
cub*_*b33 14
上面的答案对我不起作用。相反,我使用了:
mounted() {
window.addEventListener('resize', () => {
this.windowHeight = window.innerHeight
})
}
Run Code Online (Sandbox Code Playgroud)
这可能真的太晚了,但如果你想要一种更简单的方法,你可以进行 npm 安装https://www.npmjs.com/package/vue-window-size
和import windowWidth from 'vue-window-size';
或者使用composition api
setup() {
const windowSize = ref(window.innerWidth)
onMounted(() => {
window.addEventListener('resize', () => {windowSize.value = window.innerWidth} )
})
onUnmounted(() => {
window.removeEventListener('resize', () => {windowSize.value = window.innerWidth})
})
return {
windowSize
}
}
Run Code Online (Sandbox Code Playgroud)
对于那些已经在使用 Vuetify 的人,您可以只观察this.$vuetify.breakpoint.width或this.$vuetify.breakpoint.height查看视口尺寸的变化。