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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With