Home > front end >  Applying padding so some Vue child components but not others
Applying padding so some Vue child components but not others

Time:09-16

I have a parent layout component for my Vue app which renders various child components, based on Vue router. I want to give some child components padding, but not others. How can I do this? Obviously, one way is to just apply the padding in the child components themselves, but this means lots of duplication of the padding code. What I'd really like is some way for the child component to tell the parent component whether it needs padding before rendering, so the parent component can apply the padding or not before it renders.

CodePudding user response:

I think the best approach is to do it in the child component. If you don't want to repeat your code you can add a class and add the padding via css to that class.

CodePudding user response:

The best way would be to write a component if it does not already exist and add a prop to it. Prop will decide which component requires padding.

CodePudding user response:

I ended up using a dynamic layout component mechanism, where each child component defines which layout it wants by wrapping its template in the appropriate helper component:

App.vue

<script setup>
    import { shallowRef } from 'vue';
    import { RouterView } from 'vue-router';
    import Navbar from '@/components/Navbar.vue';

    const layout = shallowRef('div');
</script>

<template>
    <Navbar />
    <component :is="layout">
        <RouterView @update:layout="(x) => { layout = x; }" />
    </component>
</template>

Child.vue

<script setup>
    import LayoutBoxed from '@/components/Layout/LayoutBoxed.vue';
</script>

<template>
    <LayoutBoxed>
        <h2>Child component</h2>
        <div>Hello world</div>
    </LayoutBoxed>
</template>

LayoutBoxed.vue

<script setup>
    import { onBeforeMount } from 'vue';
    import ImplLayoutBoxed from './ImplLayoutBoxed.vue';

    const emit = defineEmits(['update:layout']);
    onBeforeMount(() => {
        emit('update:layout', ImplLayoutBoxed);
    });
</script>

<template>
    <slot />
</template>

ImplLayoutBoxed.vue

<template>
    <div  style="background-color: #e3fff9; border-color: #7defb7 !important;">
        <div >
            <slot />
        </div>
    </div>
</template>
  • Related