-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctionComponent.html
More file actions
132 lines (122 loc) · 3.75 KB
/
functionComponent.html
File metadata and controls
132 lines (122 loc) · 3.75 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<!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">
<smart-item :data="data"></smart-item>
<button @click="change('img')">切换为图片组件</button>
<button @click="change('video')">切换为视频组件</button>
<button @click="change('text')">切换为文本组件</button>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
// 图片组件选项
var ImgItem = {
props: ['data'],
render: function (createElement) {
return createElement('div', [
createElement('p', '图片组件'),
createElement('img', {
attrs: {
src: this.data.url
}
})
])
}
};
// 视频组件选项
var VideoItem = {
props: ['data'],
render: function (createElement) {
return createElement('div', [
createElement('p', '视频组件'),
createElement('video', {
attrs: {
src: this.data.url,
controls: 'controls',
autoplay: 'autoplay'
}
})
]);
}
};
// 文本组件选项
var TextItem = {
props: ['data'],
render: function (createElement) {
return createElement('div', [
createElement('p', '纯文本组件'),
createElement('p', this.data.text)
]);
}
};
Vue.component('smart-item', {
// 函数化组件
functional: true,
render: function (createElement, context) {
// 根据传入的数据,智能判断显示那种组件
function getComponent() {
var data = context.props.data;
// 判断prop: data的type字段是属于那种类型的组件
if(data.type === 'img') return ImgItem;
if(data.type === 'video') return VideoItem;
return TextItem;
}
return createElement(
getComponent(),
{
props: {
// 把smart-item的props: data传给上面的智能选择的组件
data: context.props.data
}
},
context.children
)
},
props: {
data: {
type: Object,
required: true
}
}
})
var app = new Vue({
el: '#app',
data: function (){
return {
data: {}
}
},
methods: {
change: function (type) {
if (type === 'img') {
this.data = {
type: 'img',
url: 'https://raw.githubusercontent.com/iview/iview/master/assets/logo.png'
}
} else if (type === 'video') {
this.data = {
type: 'video',
url: 'http://vjs.zencdn.net/v/oceans.mp4'
}
} else if (type === 'text') {
this.data = {
type: 'text',
content: '这是一段纯文本'
}
}
}
},
created: function () {
// 初始化
this.change('img');
}
})
</script>
</html>