使用插槽prop实现组件的事件封装

子组件

1
2
3
4
5
6
7
8
9
10
Vue.component('Child', {
template: `<div>
<slot :handle='handle'></slot>
</div>`,
methods: {
handle() {
console.log(1)
}
}
})

父组件

1
2
3
4
5
6
7
var parent = new Vue({
name: 'Parent',
el: '#app',
template: `<child v-slot='{ handle }'>
<div @click='handle'>子组件</div>
</child>`
})

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.common.dev.js"></script>
<body>
<div id="app"></div>
</body>
<script>
Vue.component('Child', {
template: `<div>
<slot :handle='handle'></slot>
</div>`,
methods: {
handle() {
console.log(1)
}
}
})
var parent = new Vue({
name: 'Parent',
el: '#app',
template: `<child v-slot='{ handle }'>
<div @click='handle'>子组件</div>
</child>`
})
</script>
</html>

最后更新: 2022年11月07日 05:12