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:

https://i.sstatic.net/yvMcP.png

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

Issues encountered during the installation of Electron JS

Having trouble installing electronjs in Node.js 18 LTS and NPM 10? Getting an error message like this? PS C:\Users\Administrator.GWNR71517\Desktop\electron> npm install electron --save-dev npm ERR! code 1 npm ERR! path C:\Users& ...

Upon reloading, the dynamically generated table does not appear accurately

When a table is dynamically created using JavaScript/jQuery/html from an Ajax call, it initially displays correctly formatted. However, upon refresh/reload, the formatting of the table becomes incorrect. To address this issue, I have implemented a Promise ...

The scroll function within the inner div is malfunctioning on the Firefox browser

Scrolling within inner div is not functioning properly in the Mozilla Firefox browser. However, it works seamlessly in Chrome. Is there a workaround for enabling scrolling in Firefox? Here is the fiddle link: http://jsfiddle.net/t6jd25x9/2/ body { f ...

An error was encountered while attempting to proxy the request [HPM]

After cloning a GitHub repository, I ran npm i in both the root directory and client directories. I then created a development configuration file. However, when attempting to run npm run dev, nodemon consistently crashes with a warning about compiled cod ...

Retrieving text data in Controller by utilizing jQuery AJAX request

Text box and button for input <input type="text" class="form-control" name="ClaimNumber" placeholder="Enter a claim number" id="ClaimNumber" /> <button class="btn btnNormal" type="submit" id="btnSearch"> ...

Express API encounters an issue with multer and body-parser as req.file is undefined

I am in the process of developing an API that will need to handle file uploads along with other GET and POST requests. To manage file uploads, I am using 'multer' while utilizing 'body-parser' for all other HTTP requests. My goal is to ...

What is the method for retrieving the name of the 'Autocomplete' component in Material UI?

Currently, I am faced with the challenge of working on multiple Autocomplete MUI components and am in the process of creating a "generic" event handler that will utilize the useReducer hook to manage the state. The issue lies in the fact that the onChange ...

Error in Vue Google Maps: Marker not defined

I'm currently working on integrating a single location map using Google Maps in Vue 2 with Vue-google-maps-2. Despite using code that has successfully worked for other parts of the application where multiple markers are plotted from an array, I am enc ...

Guide on implementing file download and saving to the downloads directory in a Vue.js and Laravel 5.4 application

I am looking to make a button called View Resume that, when clicked by the user, will download the resume and store it in the downloads folder. The resume is currently stored in my table and I would like to be able to use vue.js to facilitate the download ...

The duration of time separating each individual post

After receiving approval for publish_actions on my app, I am currently attempting to comment on feed posts. Everything is functioning smoothly. Here is the code that is working: function home(token){ jQuery.ajax({ url:'https://graph.facebook.com ...

Is it the same item in one situation, but a completely different item in another?

I am currently investigating the behavior of objects in JavaScript, particularly when it comes to copying one object onto another. It seems that sometimes they behave as if they are the same object, where modifying one also modifies the other. Many resourc ...

Failure to register Express Route

I am currently using express and facing some challenges with creating routes using express.Router. Below is my index.js file (npm main file): require('dotenv').config() const express = require('express') const loaders = require('. ...

When accessing a page from a link, JavaScript sometimes does not immediately execute on the first attempt

I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I' ...

When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change. I att ...

Using React and Redux to update the state of an object with the current state

Upon mounting my component, I make a call to an API and upon success, the state is updated with the following data: { "brief":"No brief given", "tasks":[ { "_id":"5c74ffc257a059094cf8f3c2", " ...

What is the best way to retrieve a specific number of documents from MongoDB?

I am currently facing an issue with my code that is returning all news related to a company. However, I only want the first 15 elements. Is there a way to achieve this? The following code snippet retrieves all news for a company using the google-news-jso ...

Can you confirm if this is the most efficient method for loading google-analytics and jQuery?

It's not necessary for jQuery to be loaded immediately on page load: Here is what I currently have: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '...']); _gaq.pus ...

Combining Select Options with AngularJS

I am completely new to AngularJS framework and just experimenting with it. Therefore, I'm not entirely sure if my current approach is the best or right way to achieve my goal. My aim is to create a 3-level chained ajax-filled select boxes, and while ...

Leveraging ng-class with an Angular $scope attribute

My HTML structure includes: <div class="myDiv"> <div style="width:200px; height:200px;background-image:url('img/200x200/{{largeImg}}.png');" ng-class="{'magictime foolishIn': 1}"> <span> { ...

Can jQuery script be used within a WordPress page for inline execution?

Can jQuery be executed in the middle of a page (inline)? I attempted to run the following code within a custom WordPress template.... <script type="text/javascript"> jQuery(document).ready( function() { jQuery(".upb_row_bg").css("filter","blur(30 ...