Vue.native如何将原生事件绑定到组件
作者:352328759
这篇文章主要介绍了Vue.native如何将原生事件绑定到组件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
.native将原生事件绑定到组件
详见vue官网
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Vue .native 将原生事件绑定到组件</title>
</head>
<body>
<div id="swq">
<!---->
<swq @click="clickSwq">在组件上 @click 无效</swq>
<swq @click.native="clickSwq">要在组件上绑定事件, 需使用 native, @click.native</swq>
<!---->
</div>
<script type="text/x-template" id="swq-template">
<div>
<slot></slot>
</div>
</script>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script type="text/javascript">
var swq = {
template: "#swq-template",
};
var vu = new Vue({
el: "#swq",
methods: {
clickSwq() {
console.log("点击了<swq />")
}
},
components: {
swq: swq,
},
})
</script>
</body>
</html>
vue事件中的.native
.native是什么?
.native - 监听组件根元素的原生事件。
主要是给自定义的组件添加原生事件。
例子
给普通的标签加事件,然后加native是无效的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<button @click.native="clickFn">按钮</button>
</div>
<script src='vue.js'></script>
<script>
new Vue({
el:'#app',
data:{
},
methods:{
clickFn () {
console.log('点击按钮了')
}
}
})
</script>
</body>
</html>onclick事件不会触发!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<card @click.native="clickFn">按钮</card>
</div>
<script src='vue.js'></script>
<script>
Vue.component('card',{
template:'<p>这是card组件<button>按钮</button></p>'
})
new Vue({
el:'#app',
data:{
state:false
},
methods:{
clickFn (e) {
console.log(e) //打印出MouseEvent对象
if (e.target.nodeName === 'IMG') { // 可以对点击的target标签进行判断
this.dialogImageUrl = file.target.src
this.dialogVisible = true
}
}
}
})
</script>
</body>
</html>心得:
.native - 主要是给自定义的组件添加原生事件。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
