vue之插槽Slot的简单使用

前言

前面已经说了变量的传递和方法的调用,今天讲的是传一个标签slot

它的作用是在页面上占一块区位,方便切换该位置的内容,不需要搞多个页面。

正文

写个例子

1.子组件SlotDemo

<template>
  <div>
    <h3>子组件的内容</h3>
  </div>
</template>

<script>
    export default{
      name:'SlotDemo'
    }
</script>

<style>
</style>

2.父组件App.vue

<template>
  <div id="app">
    <p>父组件的内容</p>
    <SlotDemo>我想加入的内容</SlotDemo>
  </div>
</template>

<script>
import SlotDemo from './components/SlotDemo'//引入组件
export default {
  name: 'App',
  components:{
    SlotDemo  //映射组件
  },
  methods:{

  }

}
</script>

<style>
</style>

我们把子组件映射成标签和使用时,如果在标签里加入自定义内容,发现不生效

在这里插入图片描述

这时我们就需要引入插槽

在子组件中加入slot插槽占位

<template>
  <div>
    <h3>子组件的内容</h3>
    <slot>默认插槽的内容</slot>
  </div>
</template>

<script>
    export default{
      name:'SlotDemo'
    }
</script>

<style>
</style>

父组件中替换插槽的内容

<template>
  <div id="app">
    <p>父组件的内容</p>
    <SlotDemo>我想加入的内容</SlotDemo>
  </div>
</template>

<script>
import SlotDemo from './components/SlotDemo'//引入组件
export default {
  name: 'App',
  components:{
    SlotDemo  //映射组件
  },
  methods:{

  }

}
</script>

<style>
</style>

如果父组件中标签里什么内容都不写,则会默认使用slot的内容

<template>
  <div id="app">
    <p>父组件的内容</p>
    <SlotDemo></SlotDemo>
  </div>
</template>

<script>
import SlotDemo from './components/SlotDemo'//引入组件
export default {
  name: 'App',
  components:{
    SlotDemo  //映射组件
  },
  methods:{

  }

}
</script>

<style>
</style>

在这里插入图片描述

可以使用多个插槽,只需要定义不同的名字

<template>
  <div>
    <h3>子组件的内容</h3>
    <slot name="s1">插槽1</slot>
    <slot name="s2">插槽2</slot>
    <slot name="s3">插槽3</slot>
  </div>
</template>

<script>
    export default{
      name:'SlotDemo'
    }
</script>

<style>
</style>

在使用时指定插槽 就可以了

<template>
  <div id="app">
    <p>父组件的内容</p>
    <SlotDemo>
      <div slot="s1">JAVA</div>
      <div slot="s2">VUE</div>
    </SlotDemo>
  </div>
</template>

<script>
import SlotDemo from './components/SlotDemo'//引入组件
export default {
  name: 'App',
  components:{
    SlotDemo  //映射组件
  },
  methods:{

  }

}
</script>

<style>
</style>

如果在使用时定义了插槽的名字又不指定那个插槽,替换的内容就不会生效

<template>
  <div id="app">
    <p>父组件的内容</p>
    <SlotDemo>
      <div >JAVA</div>
    </SlotDemo>
  </div>
</template>

<script>
import SlotDemo from './components/SlotDemo'//引入组件
export default {
  name: 'App',
  components:{
    SlotDemo  //映射组件
  },
  methods:{

  }

}
</script>

<style>
</style>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值