問題描述
vue在根組件上添加 子組件時(shí),報(bào)錯(cuò)?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">計(jì)數(shù)器:{{counte}}</button>
<site-name></site-name>
</div>
<script>
//父組件
const appRoot = {
data() {
return {
msg: "個(gè)人基本信息",
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應(yīng)用中組件的加載過程,添加子組件的順序錯(cuò)誤
解決方法
1.vue應(yīng)用組件加載順序
a.調(diào)用vue.createApp方法添加根組件創(chuàng)建應(yīng)用
app=Vue.createApp(appRoot);
b.在應(yīng)用中添加子組件
//子組件
app.component('site-name', {
props: {
//年齡
"age": {
type: Number,
required: true,
default: "18",
}
},
template: `<h2>年齡:{{ age }}</h2>`,
})
c.將應(yīng)用掛載在html頁面中
app.mount("#app");
2.解決方法:重新修改代碼書寫次序
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
<h1>{{ msg }}</h1>
<button @click="add">計(jì)數(shù)器:{{counte}}</button>
<site-name></site-name>
</div>
<script>
//父組件
const appRoot = {
data() {
return {
msg: "個(gè)人基本信息",
counte: 1,
}
},
methods: {
add() {
this.counte += 1;
}
},
}
//我調(diào)整了這行代碼的順序
app = Vue.createApp(appRoot);
//子組件
app.component('site-name', {
props: {
//年齡
"age": {
type: Number,
required: true,
default: "18",
}
},
template: `<h2>年齡:{{ age }}</h2>`,
})
app.mount('#app');
</script>
瀏覽器渲染效果