vue 父组件中的子组件发生事件,子组件可以通过$listeners来监听父组件在子组件发生的事件并且可以传递给父组件参数,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<my-child :content='content' @click='fn' @mouseenter='fn1' @click.native='fn'>
</my-child>
</div>
</body>
</html>
<script src="./node_modules/vue/dist//vue.min.js"></script>
<script>
// 组件通信:props $emit $attrs $listeners
let vm = new Vue({
el: '#app',
data: {
content: '点我'
},
components: {
'myChild': {
props: ['content'],
mounted() {
console.log(this.$listeners)
},
template: `<div>
<button @click='$listeners.click(123)'>{{content}}</button>
<button @click='$emit("click",12334)'>{{content}}</button>
<button @click='$emit("mouseenter",556)'>{{content}}</button>
</div>
`
}
},
methods: {
fn(num) {
console.log('fn iscall')
console.log(num)
},
fn1(num) {
console.log('fn1 iscall', num)
}
}
})
在这里子组件在mounted生命周期函数中监听到父组件的事件通过组件的$listeners来监听到,在子组件中可以调用父组件的方法,并且传递参数
也可以通过$emit 发射事件传递参数
</script>