scopedSlots

1,173 阅读1分钟

一、scopedSlots和 slot-scope 的区别

  • 作用相同:都是作用域插槽
  • slot-scope 是模板语法,scopedSlots 则是编程式语法
  • 使用不同:在 <template> 中使用 slot-scope,在 render() 函数中使用 scopedSlots

二、例子

子组件

<script>
export default {
  name: "BaseLayout",
  data() {
    return {
      headerText: "child header text",
      defaultText: "child default text",
      footerText: "child footer text",
    };
  },
  render(h) {
    return h("div", { class: "child-node" }, [
      // 相当于 <slot name="header" :text="headerText"></slot>
      this.$scopedSlots.header({ text: this.headerText }),
      // 相当于 <slot :text="defaultText"></slot>
      this.$scopedSlots.default(this.defaultText),
      this.$scopedSlots.footer({ text: this.footerText }),
    ]);
  },
};
</script>

父组件

<script>
import BaseLayout from "./base-layout.vue";
export default {
  name: "ScopedSlots",
  components: {
    BaseLayout
  },
  render(h) {
    return h("div", { class: "parent-node" }, [
      this.$slots.default,
      h("base-layout", {
        scopedSlots: {
          // 相当于下面代码:
          // <template #header="props">
          //   <p style="color:red">
          //     {{ props.text }}
          //   </p>
          // <template>
          header: props => {
            return h("p", { style: { color: "red" } }, [props.text]);
          },
          default: props => {
            return h("p", { style: { color: "deeppink" } }, [props]);
          },
          footer: props => {
            return h("p", { style: { color: "orange" } }, [props.text]);
          }
        }
      })
    ]);
  }
};
</script>
  • 页面展示效果

image.png

  • 渲染出的HTML节点 image.png

三、Vue 支持

  • devDependencies 安装 @vue/babel-plugin-jsx 包
  • babel.config.js 新增jsx 支持,如下所示
plugins: [
    ["@vue/babel-plugin-jsx"]
  ],