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

Utilizing AngularJS with dual controllers within a single view

I recently started working on an angularJS web app using a purchased template that has all its controllers, routes, and directives in a single file called app.js. This is my first dive into angularJS and front-end development. Hoping to become a Full Stac ...

Obtaining numerical values from a string with the help of Selenium IDE

I've gone through numerous solutions for this issue and attempted all of them, but none seem to be effective. Despite its seemingly simple nature, I am struggling with the following task; My objective is to extract a numerical value from a string and ...

How can scripts be used to enable fullscreen in PhoneGap?

Can JavaScript in PhoneGap enable fullscreen mode and hide the status bar? While I know it can be pre-defined in config.xml, I'm unsure if it can be changed dynamically. I've come across resources suggesting that plug-ins are necessary here, but ...

Leveraging the capabilities of Express functions on the client side through the require method in Node.js

Trying to access the configuration variables set in the file named test.js which contains -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now, I am attempting to access it upon an OnClick event taking place ...

What are some ways to incorporate JQuery with getElementById?

i am trying to retrieve all input elements within a form using JavaScript formEditable = document.getElementById("formid").getElementsByTagName("input"); However, I would like to achieve the same result using jQuery instead formEditable = $("#formid").f ...

Phonegap: Displaying audio controls and metadata for my audio stream on the lock screen and in the drop-down status bar

After successfully creating my initial android app for phonegap 5.1 that plays an audio stream, I am currently facing an issue. I am unable to locate any solutions: How can I display audio controls and metadata of my audio stream on the lock screen as well ...

Issue: ngModel: Unassignable Value

I am currently working on a piece of code that dynamically generates a drop-down list. My goal is to set the selected value using ng-repeat. In order to achieve this, I have implemented a function in ng-model. However, I am encountering an issue with the f ...

ExpressJS and cookies - Struggling to initialize a cookie with express-cookie

I recently followed a tutorial on YouTube (https://youtu.be/hNinO6-bDVM?t=2m33s) that demonstrated how to display a cookie in the developer tools Application tab by adding the following code snippet to the app.js file: var session = require('express- ...

After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I&apos ...

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

Choose the preselected value in an AJAX dropdown menu

i need to set default values in a select options dropdown. Using Ajax: $.ajax({ type: "GET", url: "teachers/" + $(this).attr("value") + "/edit", dataType: 'json', success: function ...

I'm trying to find a way to access a particular field within an HTML document using JavaScript in Node.js. Can anyone

<Response> <SMSMessageData> <Message>Delivered to 1/1 Total Cost: NGN 2.2000</Message> <Recipients> <Recipient> <number>+9109199282928</number> <cost>NGN 2.2000&l ...

Preserve the XHR-generated configuration when the browser is refreshed

My PHP page features a navigation menu with options such as Home, About Us, and Profile. When clicking on the "About Us" link from the home page, it loads an Ajax response displaying the information without reloading the page. However, if the user decide ...

What is the best way to send and configure GET information when the characters in a URI surpass 5,000?

Currently, I am utilizing a Laravel blade template. However, I encountered an error in my code when the size of the textarea item is quite large. I'm in search of a solution to resolve this issue. Hey everyone! Can you guide me on how to successfull ...

ESLint consistently raising key-spacing error consistently

Within my .eslintrc file, I have the following code: 'key-spacing': [ 'error', { 'singleLine': { 'beforeColon' : false, 'afterColon' : true }, &apos ...

apply background color to Vue list

Can anyone assist me with changing the background color of an active list item? I would greatly appreciate any help. I am currently utilizing the v-for directive in an HTML tag to display a list generated from a data function. However, I am puzzled on how ...

JavaScript event/Rails app encounters surprising outcome

I have encountered a strange bug in my JavaScript code. When I translate the page to another language by clicking on "English | Русский" using simple I18n translation, my menu buttons stop working until I reload the page. I suspect that the issue ...

Is there a method to incorporate connection parameters into every query that is run by eloquent and Laravel?

In our Laravel project, we are using SQL server as the database for connecting. The necessary connection properties that need to be set before all eloquent queries and raw Laravel queries are: SET NOCOUNT ON; SET ANSI_NULLS ON; SET ANSI_PADDING ON; SET ANS ...

Improve the efficiency of the function for retrieving data from a lengthy string and organizing it into key-value pairs within an object

I am dealing with a string extracted from a text file, which is structured in the following way on each line. 1=abc|2=TsMarketDataCache|3=1|4=141061|6=2023-02-27T05:04:50.472|36=F|7=1584A Format: key1=value1|key2=value2|key3=value3|key4=value4...|keyN=va ...

Show items in the sequence of clicking

Is there a way to display elements in the order they're clicked, rather than their order in the HTML using jQuery? For example: CSS code: .sq{ display:none; } HTML Code: <a href="#" id="1">A</a> <a href="#" id="2">B</a> ...