Npcink Blog
切换菜单

VUE 控制台报错:Uncaught TypeError: app.component is not a function

本页目录5 节

问题描述

vue 在根组件上添加 子组件时,报错 Uncaught TypeError: app.component is not a function

问题代码

<script src="https://unpkg.com/vue@next"></script>
<div id="app">
<h2>{{ msg }}</h2>
<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">
<h2>{{ msg }}</h2>
<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>

浏览器渲染效果

原网页中的可执行演示已停用,以下完整保留为静态 HTML 代码。

<script src="https://unpkg.com/vue@next"></script>
<div id="app">
<h2>{{ msg }}</h2>
<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>

参考文章