- 如果子组件调用了没有内容的插槽,若想设置默认值,可在slot标签添加默认显示的内容,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>20</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
// slot 插槽
// 父模板里调用的数据属性,使用的都是父模板的数据
// 子模板里调用的数据属性,使用的都是子模版里的数据
const app = Vue.createApp({
data() {
return {
text: '提交'
}
},
template: `
<myform>
<div>{{text}}</div>
</myform>
<myform>
<button>{{text}}</button>
</myform>
<myform></myform>
`
});
app.component('myform', {
methods:{
handleClick() {
alert(123)
}
},
template: `
<div>
<input />
<span @click="handleClick">
<slot>default value</slot>
<span>
</div>
`
})
const vm = app.mount('#root')
</script>
</body>
</html>
2. 插槽显示顺序及位置问题描述
1)父组件中有页面header和footer的内容
2)子组件有页面content的内容
3)子组件想按照header footer content的顺序显示页面内容
4)如果直接引用父组件的插槽:顺序会变成header footer content
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>20</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
// slot 插槽
// 父模板里调用的数据属性,使用的都是父模板的数据
// 子模板里调用的数据属性,使用的都是子模版里的数据
const app = Vue.createApp({
template: `
<layout>
<div>header</div>
<div>footer</footer>
</layout>
`
});
app.component('layout', {
template: `
<div>
<slot></slot>
<div>content</content>
</div>
`
})
const vm = app.mount('#root')
</script>
</body>
</html>
3. 解决2中的问题:
1)父组件告诉子组件将slot分成两个部分:
const app = Vue.createApp({
template: `
<layout>
<template v-slot:header>
<div>header</div>
</template>
<template v-slot:footer>
<div>footer</footer>
</template>
</layout>
`
});
注:可以简写成:
const app = Vue.createApp({
template: `
<layout>
<template #header>
<div>header</div>
</template>
<template #footer>
<div>footer</footer>
</template>
</layout>
`
});
2)子组件调用时说明使用哪个slot
app.component('layout', {
template: `
<div>
<slot name="header"></slot>
<div>content</content>
<slot name="footer"></slot>
</div>
`
})
之后便可看到拆分slot后的页面内容