VueJS Read Dom Attributes

若如初见. 提交于 2020-01-02 04:45:26

问题


I want to get the href attribute to the 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');
    },
}
});

Target event does not select a element. It selects the clicked element.


回答1:


You want event.currentTarget, not event.target. Here's a fiddle of the situation: https://jsfiddle.net/crswll/553jtefh/




回答2:


This is "Vue way". Vue is about reusable components. So, create component first:

<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>



回答3:


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>


来源:https://stackoverflow.com/questions/39357415/vuejs-read-dom-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!