vue.js - 带有点击监听器的无渲染 Vue 组件

标签 vue.js vuejs2 vue-component

我已经阅读了这篇深入探讨无渲染组件的文章:

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/

相关文章:

css - Vuetify 网格列换行填充全高

javascript - 为元素动态创建工具提示

javascript - VueJS 2 中 <template> 中的 <template> 有什么用?

vue.js - 在 VueJS 中,分配新数据时,v-for 不会创建离散项

vue.js - 何时将 Vue 组件拆分为多个组件(子组件)

javascript - Vue.js 3 - 为什么在这种情况下导入 vue-router 不起作用?

javascript - 在 laravel 6.x 中渲染多个 vue 组件

vue.js - 我该如何解决 "Interpolation inside attributes has been removed. Use v-bind or the colon shorthand"? Vue.js 2

javascript - 如何使用 Vue JS 为向导类型表单制作动画

vue.js - vue multiselect 1.1.4,通过id选择值