2019-04-03 13:33:42 1784浏览
今天扣丁学堂HTML5培训老师给大家介绍一下关于vue中插槽slot的理解和使用方法,文中通过示例代码介绍的非常详细,Vue的slot插槽,可以从字面意思来了解用途,占用占坑的意思,既然是占坑肯定是先占坑后面有其他具体的内容来替换代替。根据slot的应用场景可以分为匿名slot和具名slot。
<template>
<div id="app">
<div>
<input type="text" v-model="info">
<button @click="handleClick">添加</button>
</div>
<todolist v-for="item in list" :key="item" :message="msg">
<template v-slot:item="itemProps" >
<!-- tips1:<span>即为插槽内容
tips2:item是插槽的名字,为具名插槽,可对应插入到子组件中具体的插槽位置
tips3:itemProps可以获取到子组件(即插槽 prop)传出来的状态(值),
插槽 prop 的对象命名为 itemProps,可任意命名,itemProps变量存在于 <template> 作用域中
-->
<span :style="{fontSize: '20px', color: itemProps.checked ? 'red': 'blue'}">{{item}}</span>
</template>
</todolist>
</div>
</template>
<script>
import todolist from './components/todolist.vue';
export default {
name: 'App',
components: {
todolist
},
data(){
return {
msg: '4-2-05',
info: '',
list: [],
}
},
methods: {
handleClick() {
// 获取到input输入的东西,然后加入到数组中
this.list.push(this.info);
this.info = ''
}
},
}
</script>
<style>
</style>
<template>
<div>
{{message}}
<li class="item">
<input type="checkbox" v-model="checked">
<slot name="item" v-bind="{checked}" ></slot>
<!--插槽内容能够访问子组件中才有的数据是很有用的,又因为父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的
所以得想办法获取到子组件的数据。-->
<!--给子组件绑定一个动态参数,checked作为一个 <slot> 元素的特性绑定上去,绑定在 <slot> 元素上的特性被称为插槽 prop-->
</li>
</div>
</template>
<script>
export default {
props: ['item','message'],
// 因为父组件在插槽内容里使用item, 即此句代码<span>{{item}}</span>
// 相当于需要传递给子组件的内容,也就是通常的父子组件通信,所以在子组件需要通过props来获取
data() {
return {
checked: false,
}
},
created() {
console.log(this.message);
}
}
</script>
<style scoped>
.item {
color: red;
}
li{
list-style: none;
}
</style>
<slot name="header"></slot> <slot name="content"></slot> <slot ></slot> //一个不带 name 的 <slot> 出口会带有隐含的名字“default”。
- <template v-slot> can only appear at the root level inside the receiving the component(slot的只能出现在接受组件的根级别)
【扫码进入HTML5前端开发VIP免费公开课】 【扫码进入前端H5架构师进阶VIP体验课】