Ste*_*n-v 5 vue.js vue-component vuejs2
我已经阅读了这篇关于无渲染组件的文章:
https://adamwathan.me/renderless-components-in-vuejs/
无法渲染的组件看起来像这样:
export default {
render() {
return this.$scopedSlots.default({})
},
}
Run Code Online (Sandbox Code Playgroud)
现在,我想使用此无渲染组件,而且还向添加到插槽中的内容添加一个Click侦听器。
就我而言,这将是一个按钮。我的无渲染组件将只包装一个按钮并向其添加一个单击侦听器,这将依次执行AJAX请求。
如何将点击侦听器添加到正在传递到广告位的元素中?
假设您想在无渲染组件中绑定点击处理程序,我认为从这篇文章中您需要克隆传入的 vnode renderless,以增强它的属性。
参见createElements Arguments,第二个 arg 是要增强的对象
与您将在模板中使用的属性相对应的数据对象。选修的。
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');Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
347 次 |
| 最近记录: |