Javascript 单击获取html5属性时的Vue js

Javascript 单击获取html5属性时的Vue js,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我正在使用vuejs最新版本做一个项目。在这个项目中,我想得到html5属性关联的vue点击事件 我的按钮代码是 <a href="javascript:" class="btn btn-info btn-xs" @click="editModal" data_id="{{$staff->id}}"> <i class="fa fa-pencil"></i

我正在使用vuejs最新版本做一个项目。在这个项目中,我想得到html5属性关联的vue点击事件

我的按钮代码是

<a href="javascript:" class="btn btn-info btn-xs" @click="editModal"
                                           data_id="{{$staff->id}}">
          <i class="fa fa-pencil"></i>
</a>
在我的控制台中,我没有定义。如何获得正确的值。

实例作为第一个参数传递给单击事件处理程序。使用
getAttribute
函数访问属性
MouseEvent.target
将指向
MouseEvent.currentTarget
指向
(事件侦听器附加到的元素)。 将editModal方法更改为:

editModal: function(e) {
    console.log(e.currentTarget.getAttribute('data_id'));
}

顺便说一句:使用-(破折号)not_u(下划线)创建数据属性:correct is
data id
not
data_uid
您的代码中有一些错误。 让我们从HTML代码开始

当需要插值属性时,必须使用v-bind。所以你有两种方法。使用
v-bind:attribute=“expression”
或速记
:attribute=“expression”
。使用
attribute=“{{expression}}”
肯定不起作用

另一件重要的事情是,要使用自定义属性名称,您应该使用
data custom attribute name
,而不是
data\u custom-attribute-name

<div id="app">
  <a
    href="javascript:"
    class="btn btn-info btn-xs"
    @click="editModal"
    :data-id="staff.id"
    :data-my-amazing-custom-attribute="staff.name">
    Click me!
  </a>
</div>
您可以在此处检查工作版本:


希望有帮助

从数据属性中获取
id
是可以的,并且可以工作,但我的问题是,为什么?您正在使用Vue,所以请使用Vue。您可以直接传递
id

现在,您不必担心弄清楚数据属性是什么。这是在使用Vue时通常应该避免的DOM操作,因为它是不必要的

注意:我在这里假设您使用的是laravel或类似的东西,例如当呈现
{{$staff->id}
时,它会呈现为您的
id

链接。这正是向eventhandler发出值的正确方法

    <button v-on:click="$emit('enlarge-text', 0.1)">
       Enlarge text
    </button>

放大文本

有时它会返回currect值,有时它会返回未定义的
@IftakharulAlam,在我提供的示例中,对我来说,
this.$el.dataset.myAmazingCustomAttribute
解决了问题。它将是
currentTarget
而不是
target
。参考@IFTAKHARULAM thx,更新答案,没有注意到嵌套在您的问题中尝试使用
数据-
而不是
数据
,您将能够使用
e.target.dataset
new Vue({
  el: '#app',
  methods: {
    editModal: function(event){
      // Here you will be able to see all the
      // custom attributes in camelCase
      console.log(event.target.dataset);
      console.log('ID:', event.target.dataset.id);
      console.log('Name:', event.target.dataset.myAmazingCustomAttribute);
    }
  },
  data () {
    return {
      staff: {
        id: 'some id',
        name: 'Name of my amazing custom attribute'
      }
    }
  }
});
<a class="btn btn-info btn-xs" @click="editModal({{$staff->id}})">
  <i class="fa fa-pencil"></i>
</a>
methods: {
    editModal: function(id){
        console.log(id);
    }
}
    <button v-on:click="$emit('enlarge-text', 0.1)">
       Enlarge text
    </button>