Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

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?

like image 777
Lawyer Kenny Avatar asked Sep 02 '25 08:09

Lawyer Kenny


1 Answers

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

like image 118
You Nguyen Avatar answered Sep 04 '25 23:09

You Nguyen