一、父组件
- 创建父组件的实例如下:
<script>
const app = Vue.createApp({
template: `<div>hello world</div>`
});
const vm = app.mount('#root')
</script>
- 定义两个全局子组件‘hello’和’world’
<script>
const app = Vue.createApp({
template: `<div>hello world</div>`
});
app.component('hello', {
template: `<div>hello</div>`
})
app.component('world', {
template: `<div>world</div>`
})
const vm = app.mount('#root')
</script>
- 调用子组件:直接用子组件标签就可调用
<script>
const app = Vue.createApp({
template: `<div><hello/><world/></div>`
});
app.component('hello', {
template: `<div>hello</div>`
})
app.component('world', {
template: `<div>world</div>`
})
const vm = app.mount('#root')
</script>
注:通过app.component定义的组件是全局组件,在哪里都可以使用,但是这种全局创建的组件对性能会有影响
- 定义局部组件:注册后才能使用,性能比较高,使用起来比较麻烦
<!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>14</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
const Counter = {
data() {
return {
count: 1
}
},
template: `<div @click="count += 1">{{count}}</div>`
}
const app = Vue.createApp({
components: {counter: Counter},
template: `<div><counter/></div>`
});
const vm = app.mount('#root')
</script>
</body>
</html>
自定义子组件的标签
<script>
const Counter = {
data() {
return {
count: 1
}
},
template: `<div @click="count += 1">{{count}}</div>`
}
const app = Vue.createApp({
components: {'dell': Counter},
template: `<div><dell /></div>`
});
const vm = app.mount('#root')
</script>