我是靠谱客的博主 务实墨镜,这篇文章主要介绍vue 使用slot 实现一个简单的panel,现在分享给大家,希望可以做个参考。

原文链接: vue 使用slot 实现一个简单的panel

上一篇: vue slot 在子组件中显示父组件传递的模板

下一篇: vue 使用ref 让父组件调用子组件的方法

使用slot实现一个简单的panel组件

父级组件可以传递颜色和相应的内容

组件时独立的,所以数据也是独立的

每个组件有一个按钮,可以显示自己的header

160431_bocQ_2856757.png

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!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>

最后

以上就是务实墨镜最近收集整理的关于vue 使用slot 实现一个简单的panel的全部内容,更多相关vue内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(94)

评论列表共有 0 条评论

立即
投稿
返回
顶部