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

Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked. $(&apos ...

Tracking the progress of reading position using Jquery within an article

Here is an example of a reading progress indicator where the width increases as you scroll down the page: http://jsfiddle.net/SnJXQ/61/ We want the progress bar width to start increasing when the article content div reaches the end of the article c ...

Issues with setSelectionRange functionality in JavaScript unit tests leading to unexpected behavior

Currently, I am utilizing the qunit framework to perform unit testing on interactions within an HTML element that has been dynamically created using jquery (specifically, var $textarea = $('')) in Chrome. Below is the code snippet I am employing ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

Viewing the JSON Data

Support: $scope.createTimeSlots = function(interval, field) { var startingTime = moment().hours(8).minutes(0); field.timeslots = []; for (var i = 0; i < interval; i++) { $scope.intervals = 60; field.timeslots.push(startingTi ...

Broadening the capabilities of jQuery through a versatile function

Currently, I am in the process of developing a generic function for my website using jQuery that will be utilized across the entire site to display success or error messages. After careful consideration, I have decided to transform this function into a plu ...

What is the best way to eliminate an object from an array of objects depending on a certain condition?

I have an array of objects structured like so: data = [ { "name":"abc", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899ba9d979b9396d4999597">[email protected]&l ...

Struggling with populating a dropdown in MVC with JSON data fetched from an API using jQuery/JavaScript

I am struggling to bind the JSON data retrieved from an API to a dropdown list. I am having trouble extracting the values for id and name from the JSON format shown below: { "categories": [ { "categories": { "id": 1, ...

Are the root options for Vue Resource being neglected?

I have set a root option in my main.js file using Vue-Resource, but the request does not seem to use this root option. Can anyone help me figure out what I am missing? Below is the code snippet: Main.js: Vue.http.options.root = 'http://api.domain.c ...

Common mistakes encountered when utilizing webpack for react development

I'm currently following the exercises in Pro MERN Stack by Apress and have come across a webpack issue. Everything was running smoothly until I introduced webpack into the mix. Now, when I execute npm run compile, I encounter the following error: > ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

Looking for matching index in rotated array

Currently, I am working on a design with a reference rectangle (colored in red). Within a rotated container div (#map), I am trying to create a duplicate rectangle (in yellow) that matches the size and position of the original "base" rectangle, regardless ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

Analyzing npm directive

I have a script that handles data replacement in the database and I need to execute it using an npm command package.json "scripts": { "database": "node devData/database.js --delete & node devData/database.js --import" ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

Instructions for integrating content into Vuetify's v-navigation-drawer

I stumbled upon this amazing codepen: https://codepen.io/carl_/pen/QWwgqBa that almost does what I need it to do. However, the issue is that there is no content or text displayed on the right side of the menu. I've tried searching for solutions online ...

What could be causing the directives module to not get properly incorporated into the Angular app module?

I am currently in the process of learning Angular and have come across some challenges with module resolution. In js/directives/directives.js, I have a directive scoped within a directives module: angular.module("directives").directive("selectList", funct ...

Troubleshooting a problem with arrays in Vue.js and axios

Hey everyone, I recently received a response from an axios call that looks like this: axios.post('/api/hr_employee/days/'+ this.period_data.year +'/'+ this.period_data.month +'?page='+this.currentPage+'&api_token=&apo ...

Successive vows

I'm trying to retrieve responses from four promises, but I currently have to call each function in sequence one after the other. In my code, you can see that I trigger the next function within the promise callback of the previously called function. H ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...