通过插槽分发内容
和 HTML 元素一样,我们经常需要向一个组件传递内容,像这样:
<alert-box>
Something bad happened.
</alert-box>
可能会渲染出这样的东西:
幸好,Vue 自定义的
<slot>
元素让这变得非常简单:
Vue.component('alert-box', {
template: `
<div class="demo-alert-box">
<strong>Error!</strong>
<slot></slot>
</div>
`
})
<!DOCTYPE html>
<html lang="zh">
<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>通过插槽分发内容</title>
<script src="./vue.js"></script>
<style>
.hzh-alert-box {
background-color: #F3BEB8;
width: 628px;
height: 42px;
border: #f3b4ad solid 1px;
padding-top: 17px;
padding-left: 23px;
}
</style>
</head>
<body>
<div id="hzh">
<alert-box>
Something bad happened.
</alert-box>
</div>
<script>
Vue.component('alert-box', {
template: `
<div class="hzh-alert-box">
<strong>Error!</strong>
<slot></slot>
</div>
`
})
new Vue({
el: '#hzh',
})
</script>
</body>
<!DOCTYPE html>
<html lang="zh">
<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>通过插槽分发内容</title>
<script src="./vue.js"></script>
<style>
.hzh-alert-box {
background-color: #7070ff;
width: 228px;
height: 42px;
border: blue solid 1px;
padding-top: 17px;
padding-left: 23px;
}
</style>
</head>
<body>
<div id="hzh">
<alert-box>
黄子涵是帅哥!
</alert-box>
</div>
<script>
Vue.component('alert-box', {
template: `
<div class="hzh-alert-box">
<strong>你好!</strong>
<slot></slot>
</div>
`
})
new Vue({
el: '#hzh',
})
</script>
</body>