VueJS Read Dom Attributes
I want to get the href attribute for a button click event.
<a v-on:click.prevent="func($event)" href="/user/all/2">
<i class="fa fa-edit"></i>
<span>Get Data</span>
</a>
Main.JS Files
new Vue({
el: 'body',
methods: {
func: function (event) {
element = event.target;
console.log(element); // Output : Select span|i|a element
href = element.getAttribute('href');
},
}
});
The target event does not select an item. It selects the item with a click.
+5
source to share
3 answers
You want event.currentTarget
, not event.target
. Here's a scenario scenario: https://jsfiddle.net/crswll/553jtefh/
+13
source to share
This is the "Vue way". Vue are reusable components. So, first create the component:
<script src="https://unpkg.com/vue"></script>
<div id="app">
<my-comp></my-comp>
</div>
<script>
// register component
Vue.component('my-comp', {
template: '<div>Just some text</div>'
})
// create instance
new Vue({
el: '#app'
})
</script>
Now add a custom attribute and read its value:
<script src="https://unpkg.com/vue"></script>
<div id="app">
<my-comp my-attr="Any value"></my-comp>
</div>
<script>
Vue.component('my-comp', {
template: '<div>aaa</div>',
created: function () {
console.log(this.$attrs['my-attr']) // And here is - in $attrs object
}
})
new Vue({
el: '#app'
})
</script>
+5
user6748331
source
to share
var app = {
func: function (event) {
console.log(event.currentTarget.id);//this will get whole html tag
console.log(event.currentTarget.href);//this will show href value
}
}
// Apps
var app_vue = new Vue({
data: app,
}).$mount("#app_vue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app_vue" v-cloak class="card" >
<a v-on:click.prevent="func" href="/user/all/2">
<i class="fa fa-edit"></i>
<span>Get Data</span>
</a>
</div>
0
source to share