vue 全局组件与局部组件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script  type="text/javascript"  src="../js/vue.js"></script>
</head>

<body>
    <div id ="app">
    
         <cpn></cpn>
        <cpn1></cpn1>
     </div>
     


     <div id="app1">
         
        <cpn1></cpn1>
     </div>

     <!-- 模板分离 通过id关联 -->
     <template id="cpn1T"> 
        <div>
            <h2>{{title}}</h2>
             <p>我是全局组件所有vue实例都可以使用</p>
             <cpn2></cpn2>
             </div>
     </template>

     <template id="cpn2T">
        <div>
            <h2>我是cpn2</h2>
            <p>我是全局组件cpn1中的子组件</p>
            </div>
     </template>

    <script>
        //创建组件构造器
        // const cpnC = Vue.extend({
        //         template: `
        //     <div>
        //         <h2>我是标题</h2>
        //         <p>我是内容</p>
            //         </div>
            //     `
            //     });
            //全局组件
            // Vue.component('cpn',cpnC);
            //直接注册全局组件并设置模板
            Vue.component('cpn1', {
                template: '#cpn1T',  //模板分离 
                data(){             //组件中有自己的data 此data是一个函数
                    return {
                        title:'我是cpn1标题'
                    }
                },
                components: {   //cpn1中的子组件cpn2
                    cpn2: {
                        template:'#cpn2T' //模板分离 
                    }
                }

            })
        


     const vm = new Vue({
        el: '#app',
        data: {
        
        },
        //局部组件  一般用局部组件且只有一个vue实例 
        components:{
            cpn:{
                template:`
                <div>
                <h2>我是标题cpn</h2>
                 <p>我是局部组件,我在vm里</p>
                 </div>
                `
            }
        },
        computed: {
        
        },
        methods: {
        
        }
     });
     const vm1 = new Vue({
        el: '#app1',
        data: {
        
        },
        // components:{
        //     cpn:cpnC
        // },
        computed: {
        
        },
        methods: {
        
        }
     });
    </script>
</body>

</html>
原文地址:https://www.cnblogs.com/lixia0604/p/15652166.html