我已经阅读了这篇深入探讨无渲染组件的文章:
https://adamwathan.me/renderless-components-in-vuejs/
无渲染组件看起来像这样:
export default {
render() {
return this.$scopedSlots.default({})
},
}
现在我想使用这个无渲染组件,但也向传递到插槽中的任何内容添加一个点击监听器。
在我的例子中,它将是一个按钮。我的无渲染组件将简单地包装一个按钮并向其添加一个点击监听器,该监听器依次执行 AJAX 请求。
我该如何为传递到插槽中的元素添加点击监听器?
最佳答案
假设您想在无渲染组件中绑定(bind)点击处理程序,我认为来自 this post您需要克隆传递给 renderless
的 vnode,以增强它的属性。
参见 createElements Arguments , 第二个参数是要增强的对象
A data object corresponding to the attributes you would use in a template. Optional.
console.clear()
Vue.component('renderless', {
render(createElement) {
var vNode = this.$scopedSlots.default()[0]
var children = vNode.children || vNode.text
const clone = createElement(
vNode.tag,
{
...vNode.data,
on: { click: () => alert('clicked') }
},
children
)
return clone
},
});
new Vue({}).$mount('#app');
<script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>
<div id="app">
<renderless>
<button type="button" slot-scope="{props}">Click me</button>
</renderless>
</div>
关于vue.js - 带有点击监听器的无渲染 Vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572740/