vue插槽,具名插槽、作用域插槽

本文详细介绍了Vue中具名插槽(用于传递自定义内容)和作用域插槽(获取组件内部数据)的使用方法,通过实例演示了如何在父子组件间灵活传递和操作数据。

vue插槽

1、具名插槽

具有名字的插槽,使用的时候可以根据名字插入到具体要插入的组件中的相应位置

//子组件(Son)
<div>
  <p>这是该组件固定的内容</p>
   //留给引用此组件,想要添加自己内容的
  <v-slot name='title'></slot>
</div>

//父组件
<Son>
    <template v-slot='title'>
        //v-slot可以简写为#,#title
        //往该组件添加我想加的内容
        <h1>我添加的title为:具名插槽的使用</h1>
    </template>
</Son>

2、作用域插槽

可以拿到封装组件时绑定的数据,数据类型是一个对象{}

//子组件
<template>
  <div>
    <p>我是Artical组件</p>
    //在封装组件时,为预留的<slot>提供属性对应的值,这种做法,叫做“作用域插槽”
    <slot name="title" :user="userList"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: {
        name: "张三",
        age: 22,
        sex: "男",
      },
    };
  },
};
</script>
//父组件
<script>
// 引入组件
import Artical from "./components/Artical.vue";

export default {
  name: "App",
  components: {
    Artical
  }
</script>
  
  
<template>
  <div id="app">
    <Artical>
      <template #title="scope">
        <p>{{ scope }}</p>
      </template>
    </Artical>
  </div>
</template>
结果:{ "user": { "name": "张三", "age": 22, "sex": "男" } }
<template>
  <div id="app">
    <Artical>
      <template #title="scope">
        <p>{{ scope.user }}</p>
      </template>
    </Artical>
  </div>
</template>
结果:{ "name": "张三", "age": 22, "sex": "男" } 

<template>
  <div id="app">
    <Artical>
      <template #title="scope">
        <p>{{ scope.user.name }}</p>
      </template>
    </Artical>
  </div>
</template>
结果:张三
### Vue2 中具名插槽作用域插槽的使用 在 Vue2 中,具名插槽(named slots)允许组件定义多个插槽并给这些插槽命名;而作用域插槽(scoped slots),则让父级可以访问子组件的数据来渲染内容。 #### 使用具名插槽 为了创建具名插槽,在子组件内通过`<template>`标签指定`v-slot:[name]`属性。下面是一个简单的例子: ```html <!-- 子组件 ChildComponent.vue --> <div> <slot name="header"></slot> <p>这里是默认的内容。</p> <slot name="footer"></slot> </div> ``` 在父组件中可以通过如下方式填充上述具名插槽: ```html <!-- 父组件 ParentComponent.vue --> <ChildComponent> <!-- 填充 header 插槽 --> <template v-slot:header> <h1>这是头部区域</h1> </template> <!-- 填充 footer 插槽 --> <template v-slot:footer> <button>点击这里</button> </template> </ChildComponent> ``` #### 结合使用具名插槽作用域插槽 当希望传递数据到父组件用于特定位置展示时,则需要用到作用域插槽。这通常涉及到从子组件向上传递一些信息作为插槽作用域变量。 考虑一个列表项组件的例子,其中每一项都可能有不同的操作按钮显示逻辑由外部决定: ```html <!-- 子组件 ListItem.vue --> <li class="list-item"> <slot :item="item" name="action-buttons"></slot> </li> <script> export default { props: ['item'] } </script> ``` 此时可以在父组件里这样写以利用这个功能: ```html <!-- 父组件 ListContainer.vue --> <ListItem v-for="(item, index) in items" :key="index" :item="item"> <template v-slot:action-buttons="{ item }"> <span v-if="item.isEditable">编辑 | 删除</span> <span v-else>查看详情</span> </template> </ListItem> ``` 在这个案例中,`{ item }`就是解构出来的来自子组件传过来的对象参数,它使得我们可以基于每条记录的具体情况定制化地构建UI[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值