Vue组件中的渲染功能无法渲染内容

时间:2019-05-06 09:51:27

标签: vue.js

代码如下:

App.vue:

<template>
  <div id="app">
    <test-component-2 :ElementType = "'div,red,25,div1'">CCCC</test-component-2>
    <hr>
    <test-component-2 :ElementType = "'h3,green,25,h3tag'">DDDD</test-component-2>
  </div>
</template>

<script>
import TestComponent2 from './TestComponent2';

export default {
    components: {
        TestComponent2
    }
}
</script>

TestComponent2.vue:

<template>
    <div>
        This is TestComponent2
    </div>
</template>

<script>
export default {
    render: (createElement) => {
        var a = this.ElementType.split(",");
        return createElement(a[0], {
            attrs: {
                id: a[3],
                style: "color: " + a[1] + ";font-size: " + a[2] + ";"
            }
        }, this.$slots.default)
    },
    props: {
        ElementType: {
            attributes: String,
            required: true
        }
    }
}
</script>

运行应用程序时,仅显示“ This is TestComponent2”,而没有“ CCCC”和“ DDDD”。

我知道我可以在模板中添加“ slot”标签,但是如何使用渲染功能呢?

1 个答案:

答案 0 :(得分:0)

请不要在render函数中使用箭头函数语法。控制台会显示this尚未定义。

  render: function(createElement) {
    var a = this.ElementType.split(",");
    return createElement(
      a[0],
      {
        attrs: {
          id: a[3],
          style: "color: " + a[1] + ";font-size: " + a[2] + ";"
        }
      },
      this.$slots.default
    );
  },

https://codesandbox.io/s/lxl9yok3r7