Vue.js 从零开始:Slot Props

上篇提到slot传入的内容都是由外层元件提供,如果内层元件slot也想使用内层资料时,就可以使用Slot Props,概念就是内层元件利用插槽的props将部份内层资料,传递给外层元件做使用。


Slot Props

参考以下程序码:

<div id="app">
  <out-text>
    <template v-slot:default="roprops">
      内层元件插槽:
      {{ roprops.ro.name }}
    </template>
  </out-text>
</div>
const app = Vue.createApp({
  data() {
    return {
      text: "外层元件",
    }
  }
});
app.component("outText",{
  template: `
    <div class="header">
      <slot :ro="product"></slot>
    </div>
  `,
  data() {
    return {
      text: "内部元件",
      product: {
        name: "名刀不知火",
        price: 200000,
        city: "普隆德拉"
      }
    };
  }
});
app.mount("#app");

  1. 内层元件定义好要传出去的资料 <slot :ro="product"></slot>:ro为自定义名称,product为内层元件的data
  2. 外层元件模板v-slot:default="roprops"接收资料,v-slot:default固定写法,roprops为自定义名称。

Slot Props搭配Component Props

<div id="app">
  <out-text :product="product">
    <template v-slot:default="{ ro, buy }">
      component props:{{ ro.name }} <br>
      slot props:{{ buy }}
    </template>
  </out-text>
</div>
const app = Vue.createApp({
  data() {
    return {
      text: "外层元件",
      product: {
        name: "名刀不知火",
        price: 200000,
        city: "普隆德拉",
        amount: 5,
      }
    }
  }
});
app.component("outText",{
  props: ['product'],
  template: `
    <div class="header">
      <slot :ro="product" :buy="buy"></slot>
    </div>
  `,
  data() {
    return {
      text: "内部元件",
      buy: ""
    };
  },
  created() {
    if(this.product.amount > 1 ){
      this.buy = "可购买";
    }else {
      this.buy = "无法购买";
    };
  }
});
app.mount("#app");
  1. 先把外层元件props到子元件使用,<out-text :product="product">props: ['product']
  2. 执行mounted()
  3. 内层定义传出去的资料<slot :ro="product" :buy="buy"></slot>(资料是外部元件data,经由内部元件props提供)。
  4. 外层模板改为物件方式接收v-slot:default="{ ro, buy }"

参考资料

六角学院
重新认识 Vue.js


<<:  Day22-不能说的秘密(四)

>>:  网页定位-30天学会HTML+CSS,制作精美网站

[Day1] Motivation

哈罗大家好,打ㄍㄟ厚,我是目前就读天大地大台科大的 Steven Meow,这是我第一次参加铁人赛,...

Day27 - 【概念篇】Keycloak使用基本概念 - 第二部分: User & Claim & Profile

本系列文之後也会置於个人网站 接着来看看爲什麽更新帐号资讯,在「快速开始」会有那些变化。 这与cl...

鬼故事 - CS 高手

鬼故事 - CS 高手 Credit: Vince mcmahon 灵感来源: UCCU Hacke...

[Day 7] .Net WhenAll 底层(2)

前言 我们今天要试着解决昨天阅读 WhenAll 留下来的两个问题 为何要 "atomic...

Day 04 Introduction to AI

Understand responsible AI Fairness - Without incor...