Vue的一些特性和方法学习,说一千道一万不如一个例子带来的直观,下面就是一个完整的例子来总结
slot各种类型的插槽用法
关于slot这个特性,理解起来要注意几点
1:slot这个特性设计的目的就是让子组件能非常方便在父组件上进行扩展,子组件的最终页面呈现极大程度依然于父组件下面的模板如何写。
2:(2.6.0以后版本弃用slot和slot-scope,改用v-slot)
<template>
<div id="helloworld">
<child1 :user="user">
<!-- 默认插槽 -->
<template>
<p>【Vue2.6 写法】向默认Slot插入的内容aaaa</p>
</template>
<!-- 作用域插槽 -->
<template v-slot:slot2="{innerUser}">
<p>【Vue2.6 写法】Hi, {{innerUser.lastName}}</p>
</template>
<!-- 具名插槽 -->
<template v-slot:slot1>
<p>【Vue2.6 写法】向具名Slot插入的内容</p>
</template>
</child1>
<child :lists="nameList">
<template slot="ss">
<p>【Vue2.6之前旧写法】具名插槽</p>
</template>
<template slot-scope="{bb}">
<span>【Vue2.6之前旧写法】</span>
<span v-if="bb.id==1">你好:<span>{{bb.name}}</span></span>
<span v-else>{{bb.name}}</span>
</template>
<!-- 这是另一种写法,其实都一样 -->
<!-- <template slot-scope="a">
<span>【V2.6之前旧写法】</span>
<span v-if='a.bb.id==1'>你好:<span>{{a.bb.name}}</span></span>
<span v-else>{{a.bb.name}}</span>
</template>-->
</child>
<child :lists="nameList">
<template v-slot:ss>
<p>【Vue2.6 新写法】具名插槽,msg{{msg}}</p>
</template>
<template v-slot="{bb}">
<span>【Vue2.6新写法】</span>
<span v-if="bb.id==1">你好:<span>{{bb.name}}</span></span>
<span v-else>{{bb.name}}</span>
</template>
</child>
</div>
</template>
<script>
import Vue from "vue";
Vue.component("child", {
props: ["lists"],
template: `
<div style="border:1px green solid">
<slot name="ss">ss</slot>
<ul>
<li v-for="item in lists" :key="item.id">
<slot :bb="item"></slot>
</li>
</ul>
</div>
`
});
Vue.component("child1", {
props: ["user"],
template: `
<div class="slot-child">
<slot>默认Slot</slot>
<slot name="slot1">具名Slot</slot>
<slot name="slot2" :innerUser="user">Hello {{user.firstName}}</slot>
</div>
`
});
export default {
name: "helloworld",
data() {
return {
nameList: [
{ id: 1, name: "孙悟空" },
{ id: 2, name: "猪八戒" },
{ id: 3, name: "沙和尚" },
{ id: 4, name: "唐僧" },
{ id: 5, name: "小白龙" }
],
user: {
firstName: 'jay',
lastName: 'chow'
},
msg: "我是MSG"
};
}
};
</script>
<style>
</style>
效果如下图