You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vue组合式API实现自适应v-container尺寸遇阻求助

问题原因

你的代码无法运行的核心问题是在computed回调内部调用了useDisplay()。Vuetify的组合式函数(如useDisplay)必须在组件的顶层作用域(<script setup>的直接顶层)调用,不能嵌套在computed、watch这类函数内部,否则无法正确获取Vuetify的上下文状态,导致屏幕尺寸判断失效。

修复后的代码
<template>
    <v-container class="bg-surface-variant">
        <v-row class="mb-6" no-gutters>
            <v-col :cols="cols[0]">
                <v-sheet class="pa-2 ma-2">
                    .v-col-{{ cols[0] }}
                </v-sheet>
            </v-col>

            <v-col :cols="cols[1]">
                <v-sheet class="pa-2 ma-2">
                    .v-col-{{ cols[1] }}
                </v-sheet>
            </v-col>
        </v-row>
    </v-container>
</template>

<script setup>
import { computed } from 'vue';
import { useDisplay } from 'vuetify';

// 必须在顶层调用useDisplay,获取屏幕尺寸状态对象
const { lg, sm } = useDisplay();

const cols = computed(() => {
    // 直接使用顶层获取的响应式状态,脚本中需显式调用.value
    return lg.value ? [3, 9]
        : sm.value ? [9, 3]
            : [6, 6]
})
</script>
关键说明
  • useDisplay()返回的是响应式对象,脚本中访问其属性时必须加上.value(模板中Vue会自动解包响应式对象,无需手动添加)
  • 组合式API规则:所有以use开头的组合式函数,都要在组件顶层作用域调用,确保依赖追踪和上下文注入正常工作

内容的提问来源于stack exchange,提问作者Ann Yan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 06:44:51