Exploring the Method of Accessing data-* Attributes in Vue.js

I have a button that, when clicked, triggers a modal to open. The content displayed in the modal is determined by the data attributes passed to the button.

Here is my button:

<button class="btn btn-info" data-toggle="modal"
  data-target="#someModal" :data-id=item.id :data-name=item.name>
  Edit
</button>

Within the modal, there are buttons that, when clicked, should execute a vuejs function with a parameter based on the data attribute.

Modal button code:

<div class="modal-footer">
    <button type="button" class="btn btn-danger"
        @click.prevent="deleteItem()" data-dismiss="modal">
        Delete
    </button>
    <button type="button" class="btn btn-warning" data-dismiss="modal">
        <span class='glyphicon glyphicon-remove'></span> Close
    </button>
</div>

In this scenario, a parameter needs to be passed to the deleteItem() function, which corresponds to the data-id obtained from the preceding button.

Modal Code:

    <div id="deleteModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Delete</h4>
                </div>
                <div class="modal-body">
                    <div class="deleteContent">
                        Are you sure you want to delete?
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn actionBtn btn-danger"
                            @click.prevent="deleteItem()"
                            data-dismiss="modal">
                            Delete <span id="footer_action_button"
                                class='glyphicon glyphicon-trash'> </span>
                        </button>
                        <button type="button" class="btn btn-warning"
                            data-dismiss="modal">
                            <span class='glyphicon glyphicon-remove'></span> Close
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

Answer №1

Coding Example

<button type="button" @click.prevent="deleteItem()" :data-id="1" data-dismiss="modal">
Delete <span id="footer_action_button" class='glyphicon glyphicon-trash'> </span>
</button>

JavaScript Function

methods:{
  deleteItem: function(){
    var id = event.target.getAttribute('data-id');
    console.log(id) // 1
  }
}

Check out the live demo here

Answer №2

If you want to dive deep into a component's properties, try adding console.log(this) inside a component function and then trigger that function with a button click.

(Check out the image below for an example of what gets printed to the console when using console.log.)

This approach allows you to access properties like the $el property, which holds the DOM element. For instance, you could enhance your component by including the following code in the mounted lifecycle hook:

mounted() {
  console.log(this);
  this.myAttribute = this.$el.getAttribute('data-attribute-name');
},

In this scenario, you would define `myAttribute` within your data object, possibly overwriting its initial value during the component's mounted() lifecycle hook:

// Set up a default value in the data method.
// This will be updated in the mounted() lifecycle hook.
data() {
  return {
    myAttribute: 'defaultvalue'
  }
}

For more information on Vue.js (v2) lifecycle hooks, check out the official documentation here.


Here is an example output from running console.log(this) within a component:

Answer №3

Another way to pass the "item.id" is shown below:

<span @click="removeItem(item.id)">Remove</span>

Answer №4

One straightforward approach is to attach the ID to the delete button

  <button type="button" class="btn btn-danger"
        @click.prevent="deleteItem(this)" :data-id=item.id data-dismiss="modal">
        Delete
   </button>

Answer №5

If you need to access the custom data attributes (data-*) on elements, you can utilize the dataset read-only property.

For a practical demonstration, you can visit StackBlitz.

Here's an example using HTML:

<button
  type="button"
  @click.prevent="deleteItem"
  :data-id="6904888"
  :data-name="'Penny Liu'"
>
  Delete
</button>

And here is how you can handle this in Vue:

methods: {
  deleteItem(event) {
    const { id, name } = event.target.dataset;
  },
},

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

Which is better: JavaScript, Json, or Html?

When working with an ASP.NET MVC view and using jQuery AJAX to update a div, the decision on whether to use a controller that returns a PartialView or JSON can depend on various factors. Consideration for both user experience and system performance is im ...

Ways to trigger a popup when a link is clicked in Vue.js?

<label class="label-set"> <input type="checkbox" class="" name="sameadr" /> I agree to all statements of <a href="#" style="color: #ee1d24"> Terms of Use </a> </label> Is there a way to trigger a popup when a user clic ...

What are the reasons for the dynamic exclusion of an element in Angular?

Can someone help me figure out why my data is not being added dynamically using ng-repeat? I have entered the "name" which should be added to the data, but it is not displaying in the UI. You can see the issue in this demo app.controller("studentcntr", ...

Organizing Vue.js components into separate files for a cleaner view model architecture

Having smooth functionality in a single file, I encountered difficulties when attempting to break up the code into multiple files and bundle it in a .vue file. Below is the final .vue file for simplicity. Here is the HTML file: <!DOCTYPE html> < ...

I am having difficulty retrieving information from the Laravel API

I am struggling to retrieve data from my Laravel application and display it in Vue CLI. While I can see the response, I am encountering difficulties when trying to show it in the Vue application. https://i.stack.imgur.com/tCgrd.png Whenever I attempt to f ...

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: Below is the code snippet: import React, { useState, Fragment } from "react"; import Sidebar from "../../User/Sid ...

Ways to update all URLs on a page with ajax functionality

My userscript is designed to modify the href of specific links on an IP-direct Google search page: // ==UserScript== // @name _Modify select Google search links // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @include http://62.0.54.118/* // ==/Us ...

Separate the iframe sessions

I am working with 6 iframes from the same domain but with different URLs and subdirectories. Each iframe sets a cookie with the same name but a different value using the HTML header "set-cookie". To prevent interference between these cookies, I need to fin ...

Using the Github API in javascript, store an image as an image by saving its base64 Data URL

I have a base64 encoded Data URL of a webp image that looks like this: data:image/webp;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs= My goal is to push this image to GitHub using their API in the form of a webp image. To clarify, I want to achi ...

I would like to automatically log out when closing the tab in Mozilla, Internet Explorer 8.0, or Chrome

Hello there, I was wondering if it's feasible to end the session and log out when I close my tab. I'd appreciate it if you could confirm whether this feature has been implemented on your end. Thank you, Manish ...

Issue with jQuery animation: Background color does not change upon scrolling

Here is my fiddle link: https://jsfiddle.net/jzhang172/owkqmtcc/5/ I am attempting to change the background color of the "content" div when scrolling anywhere within it. The goal is for the background color to change when scrolling and revert back to its ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

Is the promises functionality respected by the Nextjs API?

Greetings, I hope all is well with you. I am currently learning NEXTJS and working with its API, but I have encountered a problem. When I click too quickly, the promises seem to get stuck or encounter issues. You can see the tests in action in this brief 3 ...

I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I sta ...

The content located at “http://localhost:3000/public/static/” was restricted because of a mismatch in MIME type (text/html) which triggered the X-Content-Type-Options:nosniff protocol

https://i.stack.imgur.com/7Etn7.png Every time I try to run the server with nodemon, I keep encountering the error mentioned in the title. Below is the code snippet from the JavaScript file: const express = require('express') const path = requir ...

Attempted to utilize zipstatic but received no feedback

I attempted to utilize the Zipstatic API with jQuery in my code, as shown below. However, I am not receiving any response. Could there be something missing? jQuery(function() { jQuery("#form").hide(); jQuery("#postcode").keyup(function() { var c ...

Encountering an issue while trying to initiate npm start command for a ReactJS application on an

While attempting to deploy my node and react app on AWS ec2, I encountered an issue. The node app is working fine, but the react app is giving an error when running npm run build. I also tried using npm start, but unfortunately, it resulted in the same er ...

AngularJS Unleashed: The Art of Displaying Dynamic AJAX

Hey there, I have a concern about the best practice to show or hide an ajax loading animation while input/output operations are being performed. At present, I am managing the animation using this code: Javascript app.controller('MyController', ...

Hold off on moving forward until the content has been loaded using ajax within loops

I am facing an issue with waiting for ajax requests to complete before proceeding. My task involves iterating through all the options in five select lists. Upon selecting an option in "Select1", it dynamically loads or refreshes "Select2". The same proces ...