最近vue2.6发布,其中更新的就有插槽slot
先来理解一下什么是插槽,看一个简单例子就能理解
父组件
<div class="test">
<but-tone>hello world</but-tone>
</div>
子组件
<div class="but-tone">
<slot></slot>
</div>
在渲染时<slot><slot>将会被替换成hello world 。slost是不会被渲染的,它是用来接收父组件传过来的内容。插槽内可以包含模板代码,甚至其他组件。
编译作用域:
父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。例如这段代码,子组件是获取不到Text的。
<template>
<div class="test">
<bot-tone>{{Text}}</bot-tone>
</div>
</template>
<script>
import bottonefrom './bottone.vue'
export default{
components:{
bottone,
},
data(){
return{
Text:'hello'
}
}
}
</script>
后备内容:就是当 <slot></slot>标签中有值时,默认显示该值,当在父组件中使用新值时,将会替换掉子组件的默认值。
具名插槽:有时候一个子组件需要多个插槽,就可以使用具名插槽。比如这个官网的例子
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
具名插槽的缩写:跟 v-on
和 v-bind
一样,v-slot
也有缩写,即把参数之前的所有内容 (v-slot:
) 替换为字符 #
作用域插槽:有时让插槽内容能够访问子组件中才有的数据是很有用的。如何访问子组件的数据呢。看这个例子
//子组件
<template>
<div class="info">
<slot v-bind:userInfo="userInfo" name='user'>{{ userInfo.sex }}</slot>
</div>
</template>
<script>
export default {
name :'info',
data () {
return {
userInfo:{
name : 'Tony',
sex: 'girl',
}
}
}
}
</script>
//父组件
<user-info>
<template v-slot:user="infoData">
{{infoData.userInfo.name}}
</template>
</user-info>
这样,父组件就可以拿到子组件中的值。而且infoDate是一个该子组件传过来的值的集合,也就是说可以传多个数据。