<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>14给组件绑定原生事件</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<child @click="handleClick"></child>
</div>
<script>
Vue.component('child', {
template: '<div @click="handleChildClick">Child</div>',
methods: {
handleChildClick() {
alert('c c') //可以打印出来:在div元素上绑定的事件指的是监听的原生的事件
this.$emit('click')
}
},
})
var vm = new Vue({
el: "#app",
methods: {
handleClick() {
alert(' c') //没法被打印:在child组件绑定的事件监听的是自定义事件,自定义事件怎么被触发?
}
},
})
</script>
</body>
</html>
简洁版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>14给组件绑定原生事件</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<child @click.native="handleClick"></child>
</div>
<script>
Vue.component('child', {
template: '<div @click="handleChildClick">Child</div>',
})
var vm = new Vue({
el: "#app",
methods: {
handleClick() {
alert(' c')
// 会打印:监听的已经不是内部组件向外触发的自定义事件了,而是原生的点击事件
}
},
})
</script>
</body>
</html>
网友评论