Javascript VueJS 读取 Dom 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39357415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VueJS Read Dom Attributes
提问by Ramazan APAYDIN
I want to get the href attribute to the button click event.
我想获取按钮单击事件的 href 属性。
<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
Main.JS 文件
new Vue({
el: 'body',
methods: {
func: function (event) {
element = event.target;
console.log(element); // Output : Select span|i|a element
href = element.getAttribute('href');
},
}
});
Target event does not select a element. It selects the clicked element.
目标事件不选择元素。它选择被点击的元素。
回答by Bill Criswell
You want event.currentTarget
, not event.target
. Here's a fiddle of the situation: https://jsfiddle.net/crswll/553jtefh/
你想要event.currentTarget
,没有event.target
。这是情况的小提琴:https: //jsfiddle.net/crswll/553jtefh/
回答by Ramazan APAYDIN
This is "Vue way". Vue is about reusable components. So, create component first:
这就是“Vue方式”。Vue 是关于可重用组件的。因此,首先创建组件:
<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 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>
回答by Saidul Haque
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>