问题描述
vue在根组件上添加 子组件时,报错 Uncaught TypeError: app.component is not a function
问题代码
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
<h1>{{ msg }}</h1>
<button @click="add">计数器:{{counte}}</button>
<site-name></site-name>
</div>
<script>
//父组件
const appRoot = {
data() {
return {
msg: "个人基本信息",
counte: 1,
}
},
methods: {
add() {
this.counte += 1;
}
},
}
//子组件
app.component('site-name', {
props: {
//年龄
"age": {
type: Number,
required: true,
default: "18",
}
},
template: `<h2>年龄:{{ age }}</h2>`,
})
app = Vue.createApp(appRoot);
app.mount('#app');
</script>
问题原因
1.没有搞清楚vue应用中组件的加载过程,添加子组件的顺序错误
解决方法
1.vue应用组件加载顺序
a.调用vue.createApp方法添加根组件创建应用
app=Vue.createApp(appRoot);
b.在应用中添加子组件
//子组件
app.component('site-name', {
props: {
//年龄
"age": {
type: Number,
required: true,
default: "18",
}
},
template: `<h2>年龄:{{ age }}</h2>`,
})
c.将应用挂载在html页面中
app.mount("#app");
2.解决方法:重新修改代码书写次序
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
<h1>{{ msg }}</h1>
<button @click="add">计数器:{{counte}}</button>
<site-name></site-name>
</div>
<script>
//父组件
const appRoot = {
data() {
return {
msg: "个人基本信息",
counte: 1,
}
},
methods: {
add() {
this.counte += 1;
}
},
}
//我调整了这行代码的顺序
app = Vue.createApp(appRoot);
//子组件
app.component('site-name', {
props: {
//年龄
"age": {
type: Number,
required: true,
default: "18",
}
},
template: `<h2>年龄:{{ age }}</h2>`,
})
app.mount('#app');
</script>
浏览器渲染效果