vue slot-scope v-slot原理及用法

一直以来觉得这个vue slot-scope很神奇
如果我们写的自定义组件,应该如何利用这个slot-scope功能呢?

Home.vue父组件

<template>
  <div class="home">
    <test :fadata="user">
      <template v-slot:bar>
        <span>Hello</span>
      </template>
      <!-- 新写法 -->
      <!-- <template v-slot:foo="cc">
          <span>asdfasdf--{{cc}}</span>
        </template> -->
      <!-- 旧写法 -->
      <div slot="foo" slot-scope="slotProps">asdfasdf--{{ slotProps }}</div>
    </test>
  </div>
</template>

<script>
import test from "@/components/test.vue";

export default {
  name: "Home",
  components: {
    test,
  },
  data() {
    return {
      user: "sfsf我的props",
    };
  }
};
</script>

test.vue子组件

<template>
  <div>
    <slot name="bar"></slot>
    <!--:data="fadata"这个是关键 -->
    <slot name="foo" :data="fadata">
    </slot>
  </div>
</template>

<script>
export default {
 name: "test",
 props:{
   fadata:{
     type: String,
     default: 'zi-default'
   }
 },
 created(){
    console.error('---fa:----:',this.fadata);
  },
  data() {
    return {
      msg: "World",
    };
  },
}
</script>

<style>

</style>

就是这么用的,有问题可以微信我号yizheng369

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vueslot-scope是一个用于在父组件中传递数据给子组件的特殊属性。它允许你在父组件中定义一个插槽,并将数据传递给子组件来使用。 使用slot-scope的一般步骤如下: 1. 在父组件中定义一个插槽,并使用slot-scope属性指定一个变量名。例如: ```html <template> <div> <slot :item="item"></slot> </div> </template> ``` 在这个例子中,我们使用:item="item"将变量item传递给插槽。 2. 在子组件中使用插槽,并在插槽的内容中使用slot-scope指定的变量名。例如: ```html <template> <div> <slot-scope="props"> <p>{{ props.item }}</p> </slot-scope> </div> </template> ``` 在这个例子中,我们使用slot-scope="props"将传递给插槽的变量名设置为props,并在插槽的内容中使用props.item来访问传递的数据。 3. 在父组件中使用子组件,并在子组件标签中传递数据给插槽。例如: ```html <template> <div> <child-component> <template v-slot:item="{ item }"> <p>{{ item }}</p> </template> </child-component> </div> </template> ``` 在这个例子中,我们使用v-slot:item="{ item }"将插槽中的变量名设置为item,并在插槽的内容中使用item来访问传递给子组件的数据。 通过使用slot-scope,我们可以在父组件中传递任意类型的数据给子组件,并在子组件中使用这些数据进行渲染或其他操作。这种机制为组件之间的数据交互提供了一种灵活且强大的方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值