vue插槽的简单使用

默认插槽

1.在Category中创建插槽

复制代码
<slot>默认值<slot/>

2.在App中使用

复制代码
       <Category tittle="美食"> 
         <ul >
         <li v-for="(l,index) in foods" :key="index">{{l}}</li>
        </ul>   
        </Category> 

3.运行后的效果

4.不在app中使用插槽的效果

具名插槽,具名之意,就是给插槽附名

1.定义

复制代码
          <slot name="games">游戏</slot>  
          <slot name="foods">食物</slot>  

2.使用

javascript 复制代码
  <div class="container">
    <Category tittle="美食">
      <ul slot="foods">
        <li v-for="(l, index) in games" :key="index">{{ l }}</li>
      </ul>
    </Category>
    <Category tittle="游戏">
      <template slot="games">
        <ul>
          <li v-for="(l, index) in games" :key="index">{{ l }}</li>
        </ul>
      </template>
    </Category>
  </div>

3.运行,因为我们写了两个插槽,另一个没有被使用就展示的默认值

作用域插槽(将数据放到子组件中)

1.子组件

javascript 复制代码
<template>
    <div class="category">
          <h2>{{tittle}}分类</h2>
          <slot name="game" :shiwu="games">游戏</slot>
          <slot name="food" :youxi="foods">食物</slot>  
     
    </div>
</template>

<script>
export default {
 name:"Category",
 props:['tittle'],
   data() {
    return {
      foods: ["香蕉", "苹果", "橙子", "梨", "火锅"],
      games: ["王者", "崩铁", "原神", "火影"],
    }
}
}
</script>

<style scoped>
.category{
    background-color: skyblue;
    width: 200px;
    height: 300px;
}
h2{
    text-align: center;
    background-color: orange;
}
ul li{
    display: flex;
   justify-content: start; 
}
</style>

2.App组件

javascript 复制代码
<template>
  <div class="container">
    <Category tittle="游戏">
      <template  slot="game" slot-scope="g"> 
        <ul >
          <li v-for="(l, index) in g.shiwu" :key="index">{{ l }}</li>
        </ul>
      </template>
    </Category>

        <Category tittle="食物">
      <template slot="food" slot-scope="f" > 
        <ul>
          <li v-for="(l, index) in f.youxi" :key="index">{{ l }}</li>
        </ul>
      </template>
    </Category>
  </div>
</template>

<script>
import Category from "./components/Category";
export default {
  name: "App",
  components: { Category },
}
</script>



<style scoped>
.container {
  display: flex;
  justify-content: space-around;
}
</style>

3.运行效果

相关推荐
2分钟速写快排1 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge6663 小时前
JavaScript:BOM 详解
前端
梯度下降者3 小时前
Nuxt框架
vue.js·服务端渲染·全栈开发·混合渲染·nuxt框架
Penge6663 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge6664 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge6664 小时前
Sass 了解
前端
Penge6664 小时前
Webpack 打包从 0 到 1 实战笔记
前端
Penge6664 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge6665 小时前
Ant Design(Antd)了解
前端
wangruofeng5 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github