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

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

一、错误代码

有以下代码:

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对象;
const app = Vue.createApp(vueWatcher);
  1. 添加子组件alert-componet
app.component("alert-component", alertComponent);
  1. 挂载到vue-watcher上。
app.mount("#vue-watcher");

三、正确代码

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");

欢迎指正错误!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值