先上Vue3组件的实例代码:
代码语言:javascript复制<!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>Document</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="michael">
<michael></michael>
<sky></sky>
<blue></blue>
</div>
<script>
var app= Vue.createApp({
data(){
return {
"msg":"hello"
}
}
});
app.component('michael', {
'template':`
<div>michael</div>
`
});
app.component('sky', {
'template':`
<div>sky</div>
`
});
app.component('blue', {
'template':`
<div>blue</div>
`
});
app.mount("#michael");
</script>
</body>
</html>
注意:以上是Vue3的叠加的写法,不一定要写成链式的代码。
运行效果:
动态组件的写法:
代码语言:javascript复制<!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>Document</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<style>
.abc{
width: 100px;
height: 100px;
border: 1px solid black;
background-color: green;
color:white;
}
</style>
</head>
<body>
<div id="michael">
<!--<michael></michael>
<sky></sky>
<blue></blue>-->
<button v-for='tab in btnMsg' :key="tab" @click="tabName=tab">
{{tab}}
</button>
<component :is="tabName" class="abc"></component><!--动态组件-->
</div>
<script>
var app= Vue.createApp({
data(){
return {
"msg":"hello",
"btnMsg":["michael","sky","blue"],
"tabName":"michael"
}
}
});
app.component('michael', {
'template':`
<div>michael</div>
`
});
app.component('sky', {
'template':`
<div>sky</div>
`
});
app.component('blue', {
'template':`
<div>blue</div>
`
});
app.mount("#michael");
</script>
</body>
</html>
运行效果如下:
[小结]
- 在Vue3中,可以使用component标签进行组件输出
- component标签需要配合:is属性来指定输出的组件名称,属性值为字符串
- component标签的所有的属性都会叠加到最终输出组件内容的最外层元素上