/**PageBeginHtml Block Begin **/ /***自定义返回顶部小火箭***/ /*生成博客目录的JS 开始*/ /*生成博客目录的JS 结束*/

Vue 中的 slot 插槽

一:知识点说明


## 插槽

1. 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 <strong style="color:red">父组件 ===> 子组件</strong> 。

2. 分类:默认插槽、具名插槽、作用域插槽

3. 使用方式:

   1. 默认插槽:

      ```vue
      父组件中:
              <Category>
                 <div>html结构1</div>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot>插槽默认内容...</slot>
                  </div>
              </template>
      ```

   2. 具名插槽:

      ```vue
      父组件中:
              <Category>
                  <template slot="center">
                    <div>html结构1</div>
                  </template>

                  <template v-slot:footer>
                     <div>html结构2</div>
                  </template>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot name="center">插槽默认内容...</slot>
                     <slot name="footer">插槽默认内容...</slot>
                  </div>
              </template>
      ```

   3. 作用域插槽:

      1. 理解:<span style="color:red">数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。</span>(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

      2. 具体编码:

         ```vue
         父组件中:
         		<Category>
         			<template scope="scopeData">
         				<!-- 生成的是ul列表 -->
         				<ul>
         					<li v-for="g in scopeData.games" :key="g">{{g}}</li>
         				</ul>
         			</template>
         		</Category>

         		<Category>
         			<template slot-scope="scopeData">
         				<!-- 生成的是h4标题 -->
         				<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
         			</template>
         		</Category>
         子组件中:
                 <template>
                     <div>
                         <slot :games="games"></slot>
                     </div>
                 </template>

                 <script>
                     export default {
                         name:'Category',
                         props:['title'],
                         //数据在子组件自身
                         data() {
                             return {
                                 games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                             }
                         },
                     }
                 </script>
         ```
   ```

   ```






二:不使用插槽效果


1:界面效果

image


2:代码结构

image


3:代码内容


3.1:vue.config.js


const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  pages:{
    index:{
      // 入口
      entry:'src/main.js',
    },
  },
  //配置vue脚手架的代理服务器:开启代理服务器  此处代理服务器默认与 该脚手架启动的模拟的前端服务器 端口相同:8080
  // 方式一
  /*
   devServer:{
     proxy:'http://localhost:5000/'
  },
 */
  // 方式二 
   devServer:{
      proxy:{
           //  '/api': 请求前缀 
          '/api':{
                    target:'http://localhost:5000/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/api':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  } ,
           //  '/api': 请求前缀 
          '/demo':{
                    target:'http://localhost:5001/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/demo':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  }
      }
   },
   transpileDependencies: true,
   lintOnSave:false, /*关闭语法检查*/


})



3.2:main.js


//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'

// 引入 vue插件: vue-recource
import vueResource from 'vue-resource'

//关闭Vue生产提示
Vue.config.productionTip=false;

// 使用插件
Vue.use(vueResource);

// 创建Vm
const vm = new Vue(  {
        el:'#app',
        render: (h) => h(App),
        //添加全局事件总线对象
        beforeCreate(){
             Vue.prototype.$bus=this;
        }
   });


3.3:App.vue


<template>
  <div class="container">
    <Category title="美食"  :listData="foods"/>
    <Category title="游戏"  :listData="games"/>
    <Category title="电影"  :listData="films"/>
</div>
</template>
<script>
import Category from './components/Category.vue'


export default {
  /* 组件名 */
  name: 'App',
  /* mixin(混入)  */
  mixins: [],
  /* 配置声明子组件  */
  components: {Category},
  /* 组件间数据、方法传值接收区  */
  props: [],
  /* 数据对象:数据赋值声明  */
  data() {
    return {
      foods:['川味火锅','烧烤羊肉','炭火烤肉','清蒸海鲜'],
      games:['梦幻西游','大话西游','征途2','传奇'],
      films:['《为人师表》','《刺客》','《喜欢你》','《桃姐》']

    }
  },
  /* 计算属性:计算区  */
  computed: {},
  /* 检测区  */
  watch: {},
  /*   */
  created() { },
  /*  挂载区 */
  mounted() { },
  /*  方法区 */
  methods: {}
}
</script>

<style  lang="css">
    .container{
      display:flex;/* div 浮动 */
      justify-content: space-around; /* 主轴对齐 */
    }

</style>


3.4:Category.vue


<template>
  <div class="category">
    <h3>{{title}}分类</h3>
    <ul>

        <li  v-for="(item,index) in listData"  :key ="index">{{item}}</li>

    </ul>
  </div>
</template>
<script>
export default {
/* 组件名 */
  name: 'Category',
/* mixin(混入)  */
  mixins: [],
/* 配置声明子组件  */
  components: {},
/* 组件间数据、方法传值接收区  */
  props: ['listData','title'],
/* 数据对象:数据赋值声明  */
  data () {
    return {

    }
  },
/* 计算属性:计算区  */
  computed: {},
/* 检测区  */
  watch: {},
/*   */
  created () {},
/*  挂载区 */
  mounted () {},
/*  方法区 */
  methods: {}
}
</script>
<style scoped lang="css">

.category{
    background-color: skyblue;
    width:200px;
    height:300px;
}
h3{
    text-align:center;
    background-color: orange ;
}

</style>











三:使用插槽组件(默认插槽 slot)


1:界面效果

image


2:代码结构


image


3:代码内容

3.1 :vue.config.js


const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  pages:{
    index:{
      // 入口
      entry:'src/main.js',
    },
  },
  //配置vue脚手架的代理服务器:开启代理服务器  此处代理服务器默认与 该脚手架启动的模拟的前端服务器 端口相同:8080
  // 方式一
  /*
   devServer:{
     proxy:'http://localhost:5000/'
  },
 */
  // 方式二 
   devServer:{
      proxy:{
           //  '/api': 请求前缀 
          '/api':{
                    target:'http://localhost:5000/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/api':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  } ,
           //  '/api': 请求前缀 
          '/demo':{
                    target:'http://localhost:5001/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/demo':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  }
      }
   },
   transpileDependencies: true,
   lintOnSave:false, /*关闭语法检查*/


})



3.2:main.js


//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'

// 引入 vue插件: vue-recource
import vueResource from 'vue-resource'

//关闭Vue生产提示
Vue.config.productionTip=false;

// 使用插件
Vue.use(vueResource);

// 创建Vm
const vm = new Vue(  {
        el:'#app',
        render: (h) => h(App),
        //添加全局事件总线对象
        beforeCreate(){
             Vue.prototype.$bus=this;
        }
   });


3.3:App.vue


<template>
  <div class="container">
    <Category title="美食"   >
      <img  src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="" >
    </Category>
    <Category title="游戏"   >
      <ul>
          <li  v-for="(g,index) in games"  :key ="index">{{g}}</li>
      </ul>
    </Category>
    <Category title="电影"   >
      <video  controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
    </Category>
</div>
</template>
<script>
import Category from './components/Category.vue'


export default {
  /* 组件名 */
  name: 'App',
  /* mixin(混入)  */
  mixins: [],
  /* 配置声明子组件  */
  components: {Category},
  /* 组件间数据、方法传值接收区  */
  props: [],
  /* 数据对象:数据赋值声明  */
  data() {
    return {
      foods:['川味火锅','烧烤羊肉','炭火烤肉','清蒸海鲜'],
      games:['梦幻西游','大话西游','征途2','传奇'],
      films:['《为人师表》','《刺客》','《喜欢你》','《桃姐》']

    }
  },
  /* 计算属性:计算区  */
  computed: {},
  /* 检测区  */
  watch: {},
  /*   */
  created() { },
  /*  挂载区 */
  mounted() { },
  /*  方法区 */
  methods: {}
}
</script>
<style scoped lang="css">
    .container{
      display:flex;/* div 浮动 */
      justify-content: space-around; /* 主轴对齐 */
    }
    img{
      width:100%;
    }

    video{
       width:100%;
    }
</style>


3.4:Category.vue

<template>
  <div class="category">
    <h3>{{title}}分类</h3>
    <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
    <slot></slot>
  </div>
</template>
<script>
export default {
/* 组件名 */
  name: 'Category',
/* mixin(混入)  */
  mixins: [],
/* 配置声明子组件  */
  components: {},
/* 组件间数据、方法传值接收区  */
  props: [ 'title'],
/* 数据对象:数据赋值声明  */
  data () {
    return {

    }
  },
/* 计算属性:计算区  */
  computed: {},
/* 检测区  */
  watch: {},
/*   */
  created () {},
/*  挂载区 */
  mounted () {},
/*  方法区 */
  methods: {}
}
</script>
<style scoped lang="css">

.category{
    background-color: skyblue;
    width:200px;
    height:300px;
}
h3{
    text-align:center;
    background-color: orange ;
}

</style>






四:使用插槽组件(具名插槽slot)



1:看界面效果

image


2:代码结构

image


3:代码内容

3.1 vue.config.js


const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  pages:{
    index:{
      // 入口
      entry:'src/main.js',
    },
  },
  //配置vue脚手架的代理服务器:开启代理服务器  此处代理服务器默认与 该脚手架启动的模拟的前端服务器 端口相同:8080
  // 方式一
  /*
   devServer:{
     proxy:'http://localhost:5000/'
  },
 */
  // 方式二 
   devServer:{
      proxy:{
           //  '/api': 请求前缀 
          '/api':{
                    target:'http://localhost:5000/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/api':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  } ,
           //  '/api': 请求前缀 
          '/demo':{
                    target:'http://localhost:5001/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/demo':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  }
      }
   },
   transpileDependencies: true,
   lintOnSave:false, /*关闭语法检查*/


})



3.2:main.js


//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'

// 引入 vue插件: vue-recource
import vueResource from 'vue-resource'

//关闭Vue生产提示
Vue.config.productionTip=false;

// 使用插件
Vue.use(vueResource);

// 创建Vm
const vm = new Vue(  {
        el:'#app',
        render: (h) => h(App),
        //添加全局事件总线对象
        beforeCreate(){
             Vue.prototype.$bus=this;
        }
   });



3.3:App.vue


<template>
  <div class="container">
    <Category title="美食"   >
      <img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="" >
      <a slot="footer" href="https://www.cnblogs.com/ios9">更多美食</a>
    </Category>
    <Category title="游戏"   >
        <ul slot="center">
            <li  v-for="(g,index) in games"  :key ="index">{{g}}</li>
        </ul>
        <div class="foot" slot="footer">
            <a   href="https://www.cnblogs.com/ios9">单机游戏</a>
            <a   href="https://www.cnblogs.com/ios9">网络游戏</a>
        </div>
    </Category>
    <Category title="电影"   >
      <video slot="center" controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
      <template  v-slot:footer >  <!--  v-slot:footer  相当于    slot="footer" 且  该方法只能用户在 template组件上 -->
          <div class="foot" >
              <a   href="https://www.cnblogs.com/ios9">经典</a>
              <a   href="https://www.cnblogs.com/ios9">热门</a>
              <a   href="https://www.cnblogs.com/ios9">推荐</a>
          </div>
          <h4 >欢迎前来观影</h4>
    </template>
    </Category>
</div>
</template>
<script>
import Category from './components/Category.vue'


export default {
  /* 组件名 */
  name: 'App',
  /* mixin(混入)  */
  mixins: [],
  /* 配置声明子组件  */
  components: {Category},
  /* 组件间数据、方法传值接收区  */
  props: [],
  /* 数据对象:数据赋值声明  */
  data() {
    return {
      foods:['川味火锅','烧烤羊肉','炭火烤肉','清蒸海鲜'],
      games:['梦幻西游','大话西游','征途2','传奇'],
      films:['《为人师表》','《刺客》','《喜欢你》','《桃姐》']

    }
  },
  /* 计算属性:计算区  */
  computed: {},
  /* 检测区  */
  watch: {},
  /*   */
  created() { },
  /*  挂载区 */
  mounted() { },
  /*  方法区 */
  methods: {}
}
</script>
<style scoped lang="css">
    .container,.foot{
      display:flex;/* div 浮动 */
      justify-content: space-around; /* 主轴对齐 */
    }
    img{
      width:100%;
    }
    h4{
      text-align:center;
    }
    video{
       width:100%;
    }
</style>



3.4:Category.vue

<template>
  <div class="category">
    <h3>{{title}}分类</h3>
    <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
    <slot name="center">我是一些默认值,当使用者没有传递具体结构时,我会出现1</slot>
    <slot name="footer">我是一些默认值,当使用者没有传递具体结构时,我会出现2</slot>
  </div>
</template>
<script>
export default {
/* 组件名 */
  name: 'Category',
/* mixin(混入)  */
  mixins: [],
/* 配置声明子组件  */
  components: {},
/* 组件间数据、方法传值接收区  */
  props: [ 'title'],
/* 数据对象:数据赋值声明  */
  data () {
    return {

    }
  },
/* 计算属性:计算区  */
  computed: {},
/* 检测区  */
  watch: {},
/*   */
  created () {},
/*  挂载区 */
  mounted () {},
/*  方法区 */
  methods: {}
}
</script>
<style scoped lang="css">

.category{
    background-color: skyblue;
    width:200px;
    height:300px;
}
h3{
    text-align:center;
    background-color: orange ;
}

</style>










五:作用域插槽(slot-scope /scope)


1:看界面效果

image


2:代码结构

image


3:代码内容


3.1:vue.config.js


const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  pages:{
    index:{
      // 入口
      entry:'src/main.js',
    },
  },
  //配置vue脚手架的代理服务器:开启代理服务器  此处代理服务器默认与 该脚手架启动的模拟的前端服务器 端口相同:8080
  // 方式一
  /*
   devServer:{
     proxy:'http://localhost:5000/'
  },
 */
  // 方式二 
   devServer:{
      proxy:{
           //  '/api': 请求前缀 
          '/api':{
                    target:'http://localhost:5000/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/api':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  } ,
           //  '/api': 请求前缀 
          '/demo':{
                    target:'http://localhost:5001/',
                    // 将请求过来的url信息里的 请求前缀  格式化去除掉
                    pathRewrite:{'^/demo':''},
                    // ws:true,  //用于支持 websocket
                    // chageOrigin:true  // 用于控制请求头中的host值
                  }
      }
   },
   transpileDependencies: true,
   lintOnSave:false, /*关闭语法检查*/


})



3.2:main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'

// 引入 vue插件: vue-recource
import vueResource from 'vue-resource'

//关闭Vue生产提示
Vue.config.productionTip=false;

// 使用插件
Vue.use(vueResource);

// 创建Vm
const vm = new Vue(  {
        el:'#app',
        render: (h) => h(App),
        //添加全局事件总线对象
        beforeCreate(){
             Vue.prototype.$bus=this;
        }
   });


3.3:App.vue


<template>
  <div class="container">
    <Category title="游戏"   >
       <template  scope="Praram">  <!-- Praram 参数名命名随意 -->
            <ul >
              <li  v-for="(g,index) in Praram.slotPraram"  :key ="index">{{g}}</li>
            </ul>
       </template>
    </Category>

   <Category title="游戏"   >
        <template  scope="Praram">  <!-- Praram 参数名命名随意 -->
          <ol >
              <li style="color:red" v-for="(g,index) in  Praram.slotPraram"  :key ="index">{{g}}</li>
          </ol>
        </template>
    </Category>

    <Category title="游戏"   >
      <template  scope="{slotPraram}">  <!-- 支持结构赋值 旧的Api写法: scope-->
          <h4  v-for="(g,index) in  slotPraram"  :key ="index">{{g}}</h4>
      </template>
    </Category>
    <Category title="游戏"   >
      <template  slot-scope="{slotPraram}">  <!-- 支持结构赋值 新的api 写法:slot-scope-->
          <h4  v-for="(g,index) in  slotPraram"  :key ="index">{{g}}</h4>
      </template>
    </Category>
</div>
</template>
<script>
import Category from './components/Category.vue'


export default {
  /* 组件名 */
  name: 'App',
  /* mixin(混入)  */
  mixins: [],
  /* 配置声明子组件  */
  components: {Category},
  /* 组件间数据、方法传值接收区  */
  props: [],
  /* 数据对象:数据赋值声明  */
  data() {
    return {

    }
  },
  /* 计算属性:计算区  */
  computed: {},
  /* 检测区  */
  watch: {},
  /*   */
  created() { },
  /*  挂载区 */
  mounted() { },
  /*  方法区 */
  methods: {}
}
</script>
<style scoped lang="css">
    .container,.foot{
      display:flex;/* div 浮动 */
      justify-content: space-around; /* 主轴对齐 */
    }
    img{
      width:100%;
    }
    h4{
      text-align:center;
    }
    video{
       width:100%;
    }
</style>


3.4 :Category.vue


<template>
  <div class="category">
    <h3>{{title}}分类</h3>
      <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
      <slot  :slotPraram ="games"> 我是一些默认内容。</slot>  <!--  :slotPraram ="games": 将插槽vue里的数据传递到引用者的界面-->
  </div>
</template>
<script>
export default {
/* 组件名 */
  name: 'Category',
/* mixin(混入)  */
  mixins: [],
/* 配置声明子组件  */
  components: {},
/* 组件间数据、方法传值接收区  */
  props: [ 'title'],
/* 数据对象:数据赋值声明  */
  data () {
    return {
      games:['梦幻西游','大话西游','征途2','传奇'],

    }
  },
/* 计算属性:计算区  */
  computed: {},
/* 检测区  */
  watch: {},
/*   */
  created () {},
/*  挂载区 */
  mounted () {},
/*  方法区 */
  methods: {}
}
</script>
<style scoped lang="css">

.category{
    background-color: skyblue;
    width:200px;
    height:300px;
}
h3{
    text-align:center;
    background-color: orange ;
}

</style>


























posted @ 2023-03-20 21:58  一品堂.技术学习笔记  阅读(46)  评论(0编辑  收藏  举报