在jquery中,如果要获取 data-*** 的值可以通过 $('目标元素').data('属性名') 来获取。
在Vue中如何获取该值呢?
1.换个思路,作为参数传递。
如下代码:
<button @click="say('Hi')">say hi</button>
methods: {
say(message){
console.log(message)
}
}
2.通过e.target.dataset.*** 或者 e.target.getAttribute('data-***')来获取。
<button @click="sayBye($event)" data-msg="Bye">say bye</button> methods: { sayBye(e){ //let msg=e.target.getAttribute('data-msg'); let msg=e.target.dataset.msg; console.log(msg) } }
3.通过$refs获取。
<button @click="sayHello()" data-msg="Hello" ref="dataMsg">say hello</button> methods: { sayHello(){ let msg=this.$refs.dataMsg.dataset.msg; console.log(msg) } }
代码完整案例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" /> <meta name="format-detection" content="telephone=no,email=no,date=no,address=no"> <title>vue</title> </head> <body> <div id="app"> <button @click="say('Hi')">say hi</button> <button @click="sayBye($event)" data-msg="Bye">say bye</button> <button @click="sayHello()" data-msg="Hello" ref="dataMsg">say hello</button> </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { }, methods: { say(message){ console.log(message) }, sayBye(e){ //方法一 //let msg=e.target.getAttribute('data-msg'); //方法二 let msg=e.target.dataset.msg; console.log(msg) }, sayHello(){ let msg=this.$refs.dataMsg.dataset.msg; console.log(msg) } } }) </script> </html>
感谢阅读~~