1.匿名插槽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<App></App>
</div>
<script src="./vue.js"></script>
<script>
Vue.component('MBtn',{
template:`
<button>
<slot></slot>
</button>
`
})
const App = {
data() {
return {
title: "老爹"
}
},
template: `
<div>
<m-btn><a href="#">登录</a></m-btn>
<m-btn>注册</m-btn>
</div>
`,
}
new Vue({
el: '#app',
components: {
App
}
})
</script>
</body>
</html>
2.具名插槽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<App></App>
</div>
<script src="./vue.js"></script>
<script>
// 只要匹配到slot标签的name值 template中的内容就会被插入到这个槽中
Vue.component('MBtn', {
template: `
<button>
<slot name='submit'></slot>
<slot name='login'></slot>
<slot name='register'></slot>
</button>
`
})
const App = {
template: `
<div>
<m-btn>
<template slot='submit'>
提交
</template>
</m-btn>
<m-btn>
<template slot='login'>
<a href="#">登录</a>
</template>
</m-btn>
<m-btn>
<template slot='register'>
注册
</template>
</m-btn>
</div>
`,
}
new Vue({
el: '#app',
components: {
App
}
})
</script>
</body>
</html>
3.作用域插槽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<App></App>
</div>
<script src="./vue.js"></script>
<script>
// 已经开发了一个待办事项列表的组件,很多模块都在
// A B
// 1.之前数据格式和引用接口不变,正常显示
// 2.新功能模块增加对勾
const todoList = {
props: {
todos: Array,
defaultValue: []
},
template: `
<ul>
<li v-for='item in todos' :key='item.id'>
// 1.在子组件中插入slot标签,自定义属性绑定需要传递到父组件的当前组件的数据
<slot :itemValue = 'item'>
</slot>
{{item.title}}
</li>
</ul>
`
}
const App = {
data() {
return {
todoList: [{
title: '大哥你好么',
isComplate: true,
id: 1
},
{
title: '小弟我还行',
isComplate: false,
id: 2
},
{
title: '你在干什么',
isComplate: false,
id: 3
},
{
title: '抽烟喝酒烫头',
isComplate: true,
id: 4
}
]
}
},
components: {
todoList
},
template: `
// 2.在父组件中使用子组件
<todoList :todos='todoList'>
// 3.在子组件标签中,使用template标签,绑定v-slot属性(绑定的数据可以任意起名,v-slot属性的数据是一个对象,存放的是子组件slot插槽中自定义的属性值)
<template v-slot='data'>
// 4.使用数据
<input type="checkbox" v-model='data.itemValue.isComplate' />
</template>
</todoList>
`,
}
new Vue({
el: '#app',
components: {
App
}
})
</script>
</body>
</html>