Vue_组件学习_创建

创建组件有三种方式,但是有许多共同之处。

一、定义公有组件

方式1和2

<body>
    <div id="app">
    //调用时直接把组件名以标签的形式调用
       <mycom1></mycom1>
       <mycom2></mycom2>    
    </div>
    <script>
        //方式一,创建组件mycom1
         Vue.extend({
            template:'<h1>444</h1>'
        })
         Vue.component("mycom2",{
            template:'<h1>123</h1>'
        })
        //方式二
        Vue.component("mycom1",{
            template:'<h1>456</h1>'
        })
         
       
       
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {}
        });
    </script>
</body>

方式三:好处:写html代码时有智能提示

<body>
    <div id="app">
     //调用时直接把组件名以标签的形式调用
       <mycom3></mycom3>
    </div>
    <template id="temp">
        <div>
            <span>123</span>
            <h1>456</h1>
        </div>
    </template>
    <script>
            //方式三
        Vue.component("mycom3",{
            template:"#temp"//将template的代码写在<script>外,但是也不能写在#app中,也就是调用组建的<div>中
        })    
       
       
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {}
        });
    </script>
</body>

无论方式几,都是在template中写组件中的html代码。用component定义组件的名字和调用组件对象,三个方式是层层简化的。

定义私有组件

与定义公有组件方式三类似

<body>
   
    <div id="app2">
        <login></login>
    </div>
    
    <template id="temp2">
        <div>
            <h2>555555</h2>
        </div>
    </template>
    <script>
  
        var vm1 = new Vue({
            el: '#app2',
            data: {},
            methods: {},
            //不同之处:
            components:{
            //login:组件名,自定义
                login:{
                    template:'#temp2'
                }
            }
        });
    </script>
</body>
发布了41 篇原创文章 · 获赞 5 · 访问量 3009

猜你喜欢

转载自blog.csdn.net/qq_43573743/article/details/103170054