Lawyer Kenny
Lawyer Kenny

Reputation: 463

Is it possible to catch element attribute which I clicked in vuejs?

In vue.js, I want to use element's attribute when I click the element.

In Home.vue

<template>
   <div role_id='1' @click="role_clicked">role 1</div>
   <div role_id='2' @click="role_clicked">role 2</div>
   <div role_id='2' @click="role_clicked">role 2</div>

   <div v-html="role_detail_box">
       axios loaded content area
   </div>
</template>
<script>
    ...
    methods: {
       role_clicked: function(){
           let uri = ~~~
           let params = { role_id : ** clicked role_id!! ** }
           axios.post(uri, params).then((response) => {
               this.role_detail_box = response.data
           })
       }
    }
</script>

If at jquery, I might use $(this).attr("role_id")

how to pass the html element when click a element?

Is it true I do not handle each element in vuejs?

Upvotes: 4

Views: 257

Answers (2)

Justin Kahn
Justin Kahn

Reputation: 1349

You can simply just pass that when you set the callback. e.g.

<div role_id='1' @click="role_clicked(1)">role 1</div>

And then add it to your callback function params

role_clicked: function(id){ ... }

Upvotes: 0

Tu Nguyen
Tu Nguyen

Reputation: 10179

Try this:

<script>
    ...
    methods: {
       role_clicked: function(event){   <~~ added code here
           const role_id = event.target.getAttribute('role-id')  <~~ added code here
           let uri = ~~~
           let params = { role_id : ** clicked role_id!! ** }
           axios.post(uri, params).then((response) => {
               this.role_detail_box = response.data
           })
       }
    } 
</script>

The event handler in VueJS will automatically receive an event object which contains all the information of the target element where the event fired. Then we will use that event object to access the role_id attribute.

This line is what you need: event.target.getAttribute('role-id') .

Don't forget the event object as an input for the function:

role_clicked: function(event){ 

This is the demo: https://codesandbox.io/s/l4517y690q

Upvotes: 2

Related Questions