Implementing Vue modal within a Laravel 5.2 foreach loop

I am facing a challenge with my Laravel blade template that uses a foreach loop to create a table with data. Each row has a link that triggers a modal when clicked. However, the issue is that clicking on any link activates the modal for every row instead of specific to the clicked row. Here's the current code snippet:

@section('content')

<div id="app">
<table class="uk-table uk-table-hover">
    <thead id="table-header">
        <tr>
            <th> Number</th>
            <th> Name</th>
            <th> Updated</th>
        </tr>
    </thead>
    <tbody>
        @foreach($results as $result)
        <tr class="" id="">
            <td>
                <a id="show-modal" @click="showModal = true">{{$result['number']}}</a>
                <modal v-if="showModal" @close="showModal = false">
            </td>
            <td>
                {{$result['name']}}
            </td>
            <td>
                {{$result['updated']}}
            </td>
        </tr>
        @endforeach
    </tbody>
</table>


<!--  Modals  -->



<!-- End container -->
</div>
@endsection


@section('loadjs')
@include('js.datatables')

<script type="text/javascript">
    Vue.component('modal',{
        template: '#modal-template'
    })

    new Vue({
        el:'#app',
        data: { 
            showModal: false
        }
    })
</script>

<!-- Modals -->
<script type="text/x-template" id="modal-template">
  <transition name="modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header">
              default header
            </slot>
          </div>

          <div class="modal-body">
            <slot name="body">
              default body
            </slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              default footer
              <button class="modal-default-button" @click="$emit('close')">
                OK
              </button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</script>

@endsection

I'm seeking advice on how to modify the code so that the modal corresponds to the specific row that was clicked.

Answer №1

If you want to easily access the keys of the $results array in a foreach loop, you can do so by looping through the array and using it like this -

@section('content')

<div id="app2">
<table class="uk-table uk-table-hovering">
    <thead id="table-header">
        <tr>
            <th> ID</th>
            <th> Title</th>
            <th> Date Created</th>
        </tr>
    </thead>
    <tbody>
        @foreach($results as $index => $item)
        <tr class="" id="">
            <td>
                <a id="show-content" @click="toggleModal = {{$index}}">{{$item['id']}}</a>
                <modal v-if="toggleModal === {{$index}}" @close="toggleModal = false">
            </td>
            <td>
                {{$item['title']}}
            </td>
            <td>
                {{$item['created_at']}}
            </td>
        </tr>
        @endforeach
    </tbody>
</table>


<!-- End container -->
</div>
@endsection

....

<script type="text/javascript">
    Vue.component('modal',{
        template: '#modal-template'
    })

    new Vue({
        el:'#app2',
        data: { 
            toggleModal: false
        }
    })
</script>

@endsection

Answer №2

I haven't used Vue in a while, but it seems like you're linking the visibility of rows to a shared variable. This means that when one row is set to true, all rows will open.

Consider restructuring your Modal component so that the logic for opening rows is handled there instead of directly managing them from the table. Each row (component) can then handle its own opening when clicked, simplifying the process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The page reloads automatically following the completion of an ajax request

Hey there, I have a basic form with just a text field. When we submit the form, the data entered in the text field gets stored in the database through ajax. Although the ajax function is working properly and the data is being submitted, the page automatica ...

Effortless script to make a URL request and display the response status | using JavaScript with jQuery

Is there a way to use JavaScript or jQuery to request a URL or website address and display the response code? For example: request www.google.com if (response_code = 200) { print "website alive" } else if (response_code = 204) { print "not found"; } ...

When applying a cell formatter to change the color of a Tabulator cell, the text displayed is being

I am attempting to dynamically change the color of a tabulator cell based on its input. My initial approach was to simply try changing the cell's color. After running the following code, here is what I observed: function testFormatter(cell, formatt ...

Numerous Kendo windows are layered on top of each other, yet the text divisions within them remain distinct

I am currently working on a project that involves laying out multiple Kendo windows in rows. Specifically, I need to display 4 windows in each row and have them shift left when closed. My framework of choice is Bootstrap 3. Everything works as expected w ...

Leveraging Google's API URL within a VueJS framework

Here is a URL example: https://example-url.com When attempting to use this URL in axios, an error occurs. The request to 'https://example-url.com' has been blocked by the CORS policy due to missing 'Access-Control-Allow-Origin' heade ...

Attempting to access a particular nested page poses a challenge with Relative Path in VueJS / Laravel, especially when using Router History mode

Hey there! I have a blog site at www.blog.com as my root URL and I'm wondering about how to handle image paths. When linking images for the root URL, I use: For the root URL URL: www.blog.com Resource Path : public/img/blog-logo.png <img :src ...

Arrangement of watch attachment and $timeout binding

I recently encountered a component code that sets the HTML content using $scope.htmlContent = $sce.trustAsHtml(content). Subsequently, it calls a function within a $timeout to search for an element inside that content using $element.find('.stuff' ...

Is there a specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Leverage the power of gRPC with Node.js and TypeScript for seamless

I'm trying to implement GRPC in a Node.js and Typescript project, but I'm facing an issue with generating proto files on Windows 10 using npm. I need to run the file transpile-proto-ts.sh: #!/usr/bin/env bash OUT_DIR="./src" TS_OUT_DIR="./src" ...

Load elements beforehand without displaying them using a div

In order to efficiently manipulate my Elements using jQuery and other methods, I am exploring the idea of preloading them all first. One approach I have considered is creating a div with CSS display set to none, and placing all the elements I need for my w ...

CF component not able to accept arguments when invoked by JavaScript through cfajaxproxy

Ever since updating to ColdFusion 2016 Update 4, I've been experiencing a new issue. Here's the code snippet: <input type='button' name='btn' value='Click me' onclick='proxyFunc();'> Incorporating ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

Tips for activating a responsive object on the DOM using the Nuxt Composition API

After fetching data from the API, I noticed that my reactive form object was not updating on the DOM even though it changed in the console.log() when I refreshed the page. When the DOM is mounted, I populate my form object, but because it's a reactiv ...

Vue.js - display additional items in an array with matching titles

I am working with an array of objects, examples include: [{ title: 'foo' id: 1, name: 'anne' }, { title: 'example', id: 2, name: 'anne' }, { title: 'ex', id: 3, name: &a ...

The de-duplication feature in webpack is not functioning properly when the splitChunks cacheGroups commons option is activated

In my lerna project, I have two identical packages named p1 and p2. Both p1 and p2 utilize a 3rd party package - in this case, eosjs@beta, which is approximately 50KB in size. When I incorporate p1 into an example react project, the package size increase ...

Tips for providing support to a website without an internet connection

I am in the process of creating a sales platform for a grocery store that utilizes PHP/MySQL. I have come across some websites that are able to fully reload and function even without internet access. For instance, when I initially visited abc.com, everyth ...

Tips for creating a dynamic sidebar animation

I have recently delved into the world of web design and am eager to incorporate a sidebar into my project. While browsing through w3school, I came across a design that caught my eye, but I found myself struggling to grasp certain concepts like the 'a& ...

Combining Laravel and VueJs for a Multi-Page Application (MPA)

I have recently developed a website using a combination of Laravel and VueJs. However, I am facing some confusion regarding the most suitable routing architecture to implement. Currently, my application has the following setup: The routing system is man ...

"Troubleshooting: Click counter in HTML/Javascript unable to function

My latest HTML project is inspired by the "cookie clicker" game, and I'm working on it for a friend. So far, I've managed to get the click counter to function to some extent. Essentially, when you click on the image, the number at the bottom sho ...

What is causing jQuery toggleClass to fail in removing a class?

I have successfully implemented a Skills accordion feature, but I am now trying to add a button that toggles all the skill sections at once. However, I am facing issues with jQuery not correctly adding or removing classes on the .accordion-trigger-all elem ...