前言
前面已经说了变量的传递和方法的调用,今天讲的是传一个标签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>