Implement a simple panel component using slot
Parent component can pass color and corresponding content
Components are independent, so the data is also independent
Each component has a button that can display its own header
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="vue.js"></script>
<link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div id="app">
<panel type="danger" @show_title="show_title">
<div slot="header">header</div>
<div slot="title">hello</div>
<div slot="content">content</div>
</panel>
<panel type="dark" @show_title="show_title">
<div slot="header">header2</div>
<div slot="title">hello</div>
<div slot="content">content</div>
</panel>
<panel :type="i.type" @show_title="show_title" v-for="i,index in articles" :key="index">
<div slot="header">{{i.header}}</div>
<div slot="title">{{i.title}}</div>
<div slot="content">{{i.content}}</div>
</panel>
</div>
<template id="panel">
<div class="card mb-3" :class="[style]" style="max-width: 18rem;">
<div class="card-header" ref="header">
<slot name="header"></slot>
</div>
<div class="card-body">
<h5 class="card-title">
<slot name="title"></slot>
</h5>
<p class="card-text">
<slot name="content"></slot>
</p>
<button @click="say">显示标题</button>
</div>
</div>
</template>
<script>
let panel = {
template: '#panel',
props: ['type'],
computed: {
// 子组件不能修改父组件传递进来的值,重新设置一个变量即可
style() {
return 'bg-' + this.type
}
},
methods: {
say() {
this.$emit('show_title', this.$refs.header.innerText)
}
}
}
new Vue({
el: '#app',
data: {
articles: [
{type: 'danger', header: 'h1', title: 't1', content: 'c1'},
{type: 'light', header: 'h2', title: 't2', content: 'c2'},
{type: 'dark', header: 'h3', title: 't3', content: 'c3'},
]
},
components: {
panel
},
methods: {
show_title(val) {
console.log(val);
}
}
})
</script>
</body>
</html>