Gra*_*ent 5 vue.js vue-composition-api
我正在使用 Nuxt 构建一个项目,我需要知道包装器的大小来调整网格设置
(我想要一行,我仍然可以通过隐藏项目在纯CSS中做到这一点)
这是我第一次使用组合 API 和脚本设置
<script setup>
const props = defineProps({
name: String
})
const width = ref(0)
const wrapper = ref(null)
const maxColumns = computed(() => {
if (width.value < 800) return 3
if (width.value < 1000) return 4
return 5
})
onMounted(() => {
width.value = wrapper.value.clientWidth
window.onresize = () => {
width.value = wrapper.value.clientWidth
console.log(width.value);
};
})
</script>
<template>
<div class="category-preview" ref="wrapper">
...
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
控制台日志工作正常,调整窗口大小并刷新页面将根据大小返回 3、4 或 5,但调整大小不会触发计算值更改
我缺少什么?
在我的测试环境中,我不得不将您的引用“宽度”重命名为其他名称。之后,它确实对我有用,使用不同的方法使用事件侦听器来调整事件大小。
你可以这样做:
<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
const wrapperWidth = ref(0)
const wrapper = ref(null)
// init component
onMounted(() => {
getDimensions()
window.addEventListener('resize', debounce(() => getDimensions(), 250))
})
// remove event listener after destroying the component
onUnmounted(() => {
window.removeEventListener('resize', debounce)
})
// your computed property
const maxColumns = computed(() => {
if (wrapperWidth.value < 800) {
return 3
} else if (wrapperWidth.value < 1000) {
return 4
} else {
return 5
}
})
// get template ref dimensions
function getDimensions () {
const { width } = wrapper.value.getBoundingClientRect()
wrapperWidth.value = width
}
// wait to call getDimensions()
// it's just a function I have found on the web...
// there is no need to call getDimensions() after every pixel have changed
const debounce = (func, wait) => {
let timeout
return function executedFunction (...args) {
const later = () => {
timeout = null
func(...args)
}
clearTimeout(timeout)
timeout = setTimeout(later, wait)
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
<template>
<div ref="wrapper">
{{ maxColumns }} // will change after resize events
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5142 次 |
最近记录: |