vuejs:<tr> 的组件,如何实现?

use*_*473 8 vue.js

阅读文档和论坛数小时后……仍然没有答案。

有以下 JS/HTML:

Vue.component("my-component", {
    props: ["id"],
    
    render: function(h) {
        return h("tr", this.$slots.default);
    }
});
    
    
var vapp = new Vue();
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.4.2/dist/vue.js"></script>

<table>
    <tr is="my-component" :name="yo">
        <td>
            <span v-text="name"></span>
        </td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

使用 tr + "is" 属性指定表格内的组件,否则浏览器会将其作为无效内容提升出来。完毕

使用 render + h("tr"...) 因为 vuejs 不渲染 tr 元素,而是 table > td 并再次浏览器将其提升。完毕

现在我有 table > tr > td 渲染得很好,但是如何添加绑定到 props/data 的孩子,所以我会在屏幕上看到“yo”。

非常感谢!

Ber*_*ert 7

如果插槽中的元素需要访问组件内部的数据,则需要使用作用域插槽

由于您使用的是渲染函数,因此作用域槽可作为一个函数使用this.$scopedSlots.default(),您可以向它传递一个对象,其中包含要提供给作用域槽的数据。

您还需要在模板中定义作用域槽。这是一个例子。

Vue.component("my-component", {
    props: ["id", "name"],
    
    render: function(h) {
        return h("tr", this.$scopedSlots.default({name: this.name}));
    }
});
    
    
var vapp = new Vue({ el:"#app"});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.4.2/dist/vue.js"></script>

<div id="app">
<table>
    <tr is="my-component" :name="'yo'">
      <template scope="{name}">
        <td>
            <span v-text="name"></span>
        </td>
      </template>
    </tr>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)


Nor*_*ora 5

如果您正在使用.vue文件,您可以像这样定义表格行组件:

<template>
  <tr>{{ name }}</tr>
</template>

<script>
  export default {
    name: 'table-row',
    props: ['name'],
  };
</script>
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

<table>
  <tr is="TableRow" name="Some name here"></tr>
</table>
Run Code Online (Sandbox Code Playgroud)