The simplest way to use the render function in Vue

The code directly is as follows. The module I use is imported into cdn to introduce vue.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module">
      import Vue from "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.esm.browser.js";
      //创建全局组件child-cpn
      Vue.component("child-cpn", {        
        created() {
          console.log("子组件created");
        },
        mounted() {
          console.log("子组件mounted");
        },
        render(h) {
          console.log("子组件render");
          return h(
            "h" + this.level, // tag name
            {}, // 一些在元素或组件上的属性或事件
            //子元素内容,如果只有一个子元素可以放在数组中 如:h('h1',{},'我是几个文字')
            [
              this.$slots.default,//接收父组件中插入到默认插槽中的内容
              h("h5", { style: { color: "#ff0000" } }, "我是子组件"),
            ]
          );
        },
        props: {
          level: {
            type: Number,
            required: true,
          },
        },
      });
      const vm = new Vue({
        name: "HelloWorld",
        el: "#app",
        data: {
          message: "这条信息是父组件想在子组件中插入的信息",
          flevel: 2,
        },
        created() {
          console.log("父组件created");
        },
        mounted() {
          console.log("父组件mounted");
        },
        render(h) {
          console.log("父组件render");
          //三个参数 标签名,元素或组件上绑定的属性,子组件
          return h(
            "child-cpn",//标签为子组件
            { attrs: { level: this.flevel } },//标签上绑定的属性
            '父组件插入子组件插槽中的文字'//标签中放置的子元素内容
          );
        },
      });
    </script>
  </body>
</html>

Running the code shows that the child component is rendered in #app and the content is passed in from the parent component.

Guess you like

Origin blog.csdn.net/uniquepeng/article/details/132450082