Featured image of post Uncaught TypeError:xxx.component is not a function

Uncaught TypeError:xxx.component is not a function

Vue 3 报错Uncaught TypeError:xxx.component is not a function

Vue 3 报错Uncaught TypeError:xxx.component is not a function

记录学习Vue 3过程中踩的坑

一、错误代码

有以下代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const vueWatcher = {
    methods: {
        click(index) {
            if (index == 0) {
                alert("外层");
            } else if (index == 1) {
                alert("中层");
            } else if (index == 2) {
                alert("内层");
            }
        },
        KeyDownCtrl() {
            alert("Ctrl Pressed");
        }
    }
}
const app = Vue.createApp(vueWatcher).mount("#vue-watcher");
const alertComponent = {
    data() {
        return {
            msg: "警告",
        }
    },
    methods: {
        click() {
            alert(this.msg);
        }
    },
    template: '<div><button @click="click">按钮</button></div>'
}
app.component("alert-component", alertComponent);

我们是想要给 app对象添加一个标准的Vue组件alert-component,但是浏览器报错Uncaught TypeError:app.component is not a function

二、分析原因

其实这是一个添加子组件顺序的问题。上述错误代码中,先创建一个名为app的Vue对象,接着挂载到vue-watcher上,最后添加子组件alert-componet。 这种顺序是错误的,正确的顺序应该是:

  1. 创建一个名为app的Vue对象;
1
const app = Vue.createApp(vueWatcher);
  1. 添加子组件alert-componet
1
app.component("alert-component", alertComponent);
  1. 挂载到vue-watcher上。
1
app.mount("#vue-watcher");

三、正确代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const vueWatcher = {
    methods: {
        click(index) {
            if (index == 0) {
                alert("外层");
            } else if (index == 1) {
                alert("中层");
            } else if (index == 2) {
                alert("内层");
            }
        },
        KeyDownCtrl() {
            alert("Ctrl Pressed");
        }
    }
}
const app = Vue.createApp(vueWatcher);
const alertComponent = {
    data() {
        return {
            msg: "警告",
        }
    },
    methods: {
        click() {
            alert(this.msg);
        }
    },
    template: '<div><button @click="click">按钮</button></div>'
}
app.component("my", alertComponent);
app.mount("#vue-watcher");

欢迎指正错误!

Licensed under CC BY-NC-SA 4.0