問題描述
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>
瀏覽器渲染效果