Home > other >  How to show/hide @foreach statement
How to show/hide @foreach statement

Time:02-11

I have a Vuejs 3 dropdown reusable component. My problem is that the @foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.

To demonstrate please check this gif:

dropdown

My component in blade:


<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/">
            All
        </Dropdownitems>

        <div>
            @foreach ($categories as $category)
                <Dropdownitems
                    href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                    >
                    {{ $category->name }}
                </Dropdownitems>
            @endforeach
        </div>

    </Dropdowncontent>

</Dropdown>

I added a div to contain the @foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).

I just need a way to only display this div or the @foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?

-- EDIT --

I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade @foreach statement echoing out the results as text before the component is loaded:

<template>
    <a v-if="showLinks" href="" >
        <slot />
    </a>
</template>

<script>
export default {
    name: "Dropdownitems",
    setup() {
        const showLinks = false;

        return {
            showLinks,
        };
    },
};
</script>

<style></style>

Here is a gif to show the result of that:

foreach2

CodePudding user response:

Try with a @if directive:

Conditional Rendering

from the documentation:

<button @click="awesome = !awesome">Toggle</button>

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no            
  • Related