为什么要先写全局注册的组件再写vue实例

今天在写项目的时候发现了一个问题,先看看我下面的代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue组件</title>
</head>

<body>
    <div id="app">
        <todo-item></todo-item>
    </div>
</body>
<script src="../js/vue.js"></script>
<script>    
    new Vue({
        el: "#app",
    });
    Vue.component("todo-item", {
        template: "<h1>Hello word!</h1>"
    });
</script>
</html>

代码运行后发现浏览器上啥也没有,代码在vscode编译没有报错并且在浏览器控制器也没有任何提示错误,后来发现是实例位置和组件位置写反了,下面的是正确代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue组件</title>
</head>

<body>
    <div id="app">
        <todo-item></todo-item>
    </div>
</body>
<script src="../js/vue.js"></script>
<script>
    Vue.component("todo-item", {
        template: "<h1>Hello word!</h1>"
    });
    new Vue({
        el: "#app",
    });
</script>
</html>

结论:Vue的实例化会把全局注册的组件注册到当前实例中,当实例化完成后,再注册组件是没有用的,自定义指令、过滤器的全局注册道理也是一样的。

猜你喜欢

转载自blog.csdn.net/weixin_55992854/article/details/119107461