Search code examples
vuejs3vuetify.js

Adaptive v-container size


I'm trying to make an adaptive v-container size so that it changes depending on the screen resolution.

I use the Composition API

<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';

const cols = computed(() => {
    const { lg, sm } = useDisplay();
    return lg ? [3, 9]
        : sm ? [9, 3]
            : [6, 6]
})

</script>

Unfortunately, this code doesn't work and I don't understand why( I tried to rewrite this code using the Options API and everything worked, but for the project I need the Composition API.


Solution

  • lg and sm are refs !

    That means lg will always be truthy, but lg.value could be either true or false.

    Replace your computed with:

    const cols = computed(() => {
        const { lg, sm } = useDisplay();
        return lg.value ? [3, 9]
            : sm.value ? [9, 3]
                : [6, 6]
    })
    
    

    Edit: after reading your comment, I realized the useDisplay is not at the right place, you have to call it only once, so take it out of the computed

    
    const { lg, sm } = useDisplay();
    
    
    const cols = computed(() => {
        return lg.value ? [3, 9]
            : sm.value ? [9, 3]
                : [6, 6]
    })