Guide on displaying the value of an element in a Vue modal

I am working with a list of items displayed as <li> elements in a loop. When one of these elements is clicked, I would like a modal box to open up displaying specific content related to that particular element.

The following data represents the items in the list:


    {value: 10, name: "foo"},
    {value: 12, name: "bar"},
    {value: 14, name: "foobar"},
    {value: 22, name: "test"},
    {value: 1, name: "testtooo"},
    {value: 8, name: "something"}

Upon clicking an element, I would like to view the corresponding value property inside the modal box.

To see how this functions, I have created a fiddle here: https://jsfiddle.net/hvb9hvog/14/

Inquiry

I have successfully implemented the modal feature, but I am unsure how to display the value property of each individual element within the modal itself. Can anyone provide guidance on achieving this?

Answer №1

There are various approaches to tackle this issue, but one method is to introduce a new data property named value. When you trigger a @click event on the li element, you obtain its value, assign it to the value property, and then showcase that value in the modal's body ({{this.value}}).

You can define two @click methods, hence include another one to update the recently established data property, designated as value.

Explore this fiddle

Key code adjustments:

Within your li element:

<li v-for="request in filteredRequests">
    <a href="#" @click="showModal = true; setVal(request.value)">{{request.name}}</a>
</li>

In your modal markup:

<modal v-if="showModal" @close="showModal = false">
    <!--
    custom content could be utilized here for overriding
    default content
    -->
    <h3 slot="header">custom header</h3>
    <div slot="body">
        {{this.value}}
    </div>
</modal>

Inside vue data:

data: {
    requests: [
        {value: 10, name: "foo"},
        {value: 12, name: "bar"},
        {value: 14, name: "foobar"},
        {value: 22, name: "test"},
        {value: 1, name: "testtooo"},
        {value: 8, name: "something"}
    ],
    num: 0,
    showModal: false,
    value: 9999999999
},

Within vue methods:

methods: {
    setVal(val) {
        this.value = val;
    }
},

This script demonstrates Vue components along with related HTML and CSS styles.

Answer №2

Include the "req" property in the data

data() {
  return {
     ...
     req: {},
     ...
  }
}

Add a click event:

<a href="#" @click="showModal = true; req = request">{{request.name}}</a>

Integrate a body slot

 ...
 <h3 slot="header">custom header</h3>
 <div slot="body">
   {{req.value}}
 </div>
 ...

https://jsfiddle.net/w4e6hr86/

Answer №3

Are you unsure if your question pertains to Vue.js or just plain JS? Here are some basic examples that might help. I suggest looking into event delegation and events in vuejs for more information.

Vue Js

<template>
  <div class="content">
    <ul>
      <li v-for="item in items" @click.prevent="showModal(item)">{{ item }}</li>
    </ul>

    <div class="modal" v-show="isModalVisible">
      {{ JSON.stringify(selectedItem) }}
      <a href="#" @click.prevent="selectedItem = null">close modal</a>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'something',
    data () {
      return {
        selectedItem: item,
        items: [{
          id: 1,
          name: 'something'
        }, {
          id: 2,
          name: 'something #2'
        }]
      }
    },
    computed: {
      isModalVisible () {
        return this.selectedItem !== null
      }
    }
    methods: {
      showModal (item) {
        this.selectedItem = item
      }
    }
  }
</script>

Plain javascript

const toggleModal = content => {
  const $body = document.querySelector('body')
  const $modal = $body.querySelector('.modal')
  $modal && $modal.remove()
  $body.insertAdjacentHTML('beforeend',`<div class="modal">${content}</div>`)
}

document.querySelector('ul').addEventListener('click', e => {
  if (! e.target.matches('li')) {
    return
  }

  toggleModal(e.target.innerText)
});
  1. Explore Event delegation.
  2. Learn about insertAdjacentHtml.
  3. Read up on Vuejs Event handling

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

What are some ways to create a flashing effect for text in HTML and JavaScript?

Although flashing text is typically prohibited in many places, my client has requested it for a project. I need to create one line of text that flashes using HTML and JavaScript. The text should appear and disappear within seconds, repeating this cycle. I ...

Vuetify: Dynamic v-select options based on user selection

Here's a codepen I created as an example: https://codepen.io/rasenkantenstein/pen/qBdZepM In this code, the user is required to select a country and then choose cities only from that selected country. The data of people is stored in an array behind t ...

Trouble arises when attempting to incorporate the Restangular dependency with Angular using browserify

I've been using browserify to manage my angular dependencies successfully, however, when I try to add restangular I encounter an error: "Uncaught Error [$injector:modulerr]". Here's a glimpse of my package.json: "browser": { "angular": "./ ...

Modifying an object's attribute in React.js by toggling a checkbox

As I delve into learning React, I am constructing a straightforward todo list. Here's the object contained within my initialState: getInitialState:function(){ return { items: [ { text:"Buy Fish", ...

Building a custom error page with Laravel 10, Inertia JS, and Vue.js featuring resource routing

I recently embarked on a new project using Laravel 10, InertiaJS, and Vue3. As part of this project, I created two simple models: Blog and Listings. Although I followed a tutorial to set up the blog, I encountered some difficulties with the listings. While ...

How can I efficiently fetch data from Firebase, manipulate it through computations, and present it using React Hooks?

I am currently working on retrieving multiple "game" objects from Firebase Storage, performing statistical calculations on them, and then presenting the game statistics in a table. Here is an overview of my code structure: function calculateTeamStatistics( ...

Acquiring images from an external source and storing them in either the $lib directory or the static folder during the

Currently, I have a Sveltekit project set up with adapter-static. The content for my pages is being pulled from Directus, and my images are hosted in S3, connected to Directus for easy access. I am also managing audio samples in a similar manner. During b ...

Why is the 'a' element not clickable after the AJAX complete function has executed in JavaScript?

I have a small question regarding my use of AJAX. Everything is working fine, but after the AJAX request completes, I am trying to change the element attributes such as backgroundImage dynamically. Although this process works correctly, the element that wa ...

Updating a particular element within nested arrays: best practices

I have developed a data table containing student records using material UI. Each row represents a different student array with a fee verification button. My goal is to change the fee status when the button is clicked for a specific student, but currently t ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...

Is AngularJS not able to effectively manage the button type "reset"?

I currently have the following code snippet: <form name="editor"> <h2>Create/Update</h2> {{ editor.title.$error.required }} <div ng-class="{ 'has-error': editor.title.$invalid && editor.title.$dirty, &apo ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

Expand Elements to occupy entire width

My CSS skills are still in the early stages. I haven't delved too deeply into it. I have a query regarding how to achieve full width for an element. I've included my code below, but the basic approach I tried using 'width: 100%' didn&a ...

Show or hide the legend on a highchart dynamically

I am currently utilizing highchart in my application and I am interested in learning how to toggle the visibility of the legend within the highchart. Here is what I have attempted: var options = { chart: { type: 'column&a ...

Is it possible to dynamically call a component in Vue.js using a variable name

Can a Vue.js component be called by using a variable name? The components are registered like this: import Component1 from 'component1' import Component2 from 'component2' import Component3 from 'component3' ... components: ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Exploring the world of JSON files using JavaScript

Basically, my bot responds to a command (!accounts) by providing users with information based on their ID. For example, if an ID of 662 sends the command !account, the bot will search for steamID 662 in the json files and display the currency and correspon ...

Utilizing ng-repeat in a tabset to create an interactive and customizable tab interface

I am using angular ui tab (angular-ui.github.io/bootstrap/) and I expected that with ng-repeat, I would be able to make it dynamic, meaning the user can add tabs. However, unexpectedly it duplicates the tabs. Here is a demo: http://plnkr.co/edit/iHi1aOfbz ...

Ajax transmitting data with concealed characters

I'm trying to send data from one PHP site to another. On the first site, everything looks good. The string appears as --show="author,book,text/n However, when I check the string after receiving it on the second site, it shows --show="author,b ...

What are the steps to collapse React state in a comments section?

Here is the data I have: { "currentUser": { "image": { "png": "/src/assets/images/avatars/image-juliusomo.png", "webp": "/src/assets/images/avatars/image-juliusomo.webp" }, ...