vue 组件 全局组件和局部组件component

1、全局组件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            vue组件测试
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script type="text/javascript">
            
            //注册全局组件
            Vue.component('my-component',{
                template: '<div>我是全局组件</div>'
            })
            
            Vue.component('other-component', {
                template: '<div>我是另一个全局组件<my-component></my-component></div>'
            })
            
            new Vue({
                el:"#app",
                template:'<other-component></other-component>'
            })
            
        </script>
    </body>
</html>

显示结果:

我是另一个全局组件

我是全局组件

 

2、局部组件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            vue组件测试
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script type="text/javascript">
                
            //注册局部组件
            const child = {
                template: '<div>我是局部组件</div>'
            }
            
            new Vue({
                el:"#app",
                template:'<my-component></my-component>',
                components:{
                    'my-component': child
                }
            })
            
        </script>
    </body>
</html>

显示结果:

我是局部组件

 3、组件嵌套

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            vue组件测试
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script type="text/javascript">
                
            //注册局部组件
            const child = {
                template: '<div>我是局部child组件</div>'
            }
            
            const father = {
                template: '<div>我是father组件,我包含了:<child-component></child-component> </div>',
                components: {
                    'child-component': child
                }
            }
            const grandFather={
                template: '<div>我是grandFather组件,我包含了:<father-component></father-component> </div>',
                components: {
                    'father-component': father
                }
            }
            new Vue({
                el:"#app",
                template:'<my-component></my-component>',
                components:{
                    'my-component': grandFather
                }
            })
            
        </script>
    </body>
</html>

显示结果:

我是grandFather组件,我包含了:

我是father组件,我包含了:

我是局部child组件

参考自:https://www.cnblogs.com/penghuwan/p/7222106.html#_label0

原文地址:https://www.cnblogs.com/150536FBB/p/11328651.html