組件的創建方式

 原始方式:使用Vue.extend()方式創建組件

  /*1.使用Vue.extend({
        template:"  HTML結構 "
    })  創建組件,接收一個返回值(創建組件對象)*/

    var com = Vue.extend({
       template:'<h1>這是使用Vue.extend方式創建的組件</h1>'
    });
    /*2.使用Vue.component('自定義組件名',創建組件對象)*/
   Vue.component('myCom',com);

注意:① . 自定義組件名使用駝峯命名時,在使用的過程中需要改成小寫在前面加-

② . 無論是哪種方式創建出來的組件,組件的template屬性指向的模板內容,必須有且只有一個根元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="app">
    <!--3使用方式:用自定義組件名作爲元素標籤-->
    <my-com></my-com>
</div>
<script src="../lib/vue-2.4.0.js"></script>
<script>
    /*1.使用Vue.extend({
        template:"  HTML結構 "
    })  創建組件,接收一個返回值(創建組件對象)*/
//    var com = Vue.extend({
//        template:'<h1>這是使用Vue.extend方式創建的組件</h1>'
//    });
    /*2.使用Vue.component('自定義組件名',創建組件對象)*/
    /*注意:自定義組件名使用駝峯命名時,在使用的過程中需要改成小寫在前面加-*/
//    Vue.component('myCom',com);


    /*簡寫*/
    Vue.component('myCom',Vue.extend({
        template:'<h1>這是使用Vue.extend方式創建的組件</h1>'
    }));

    var vm = new Vue({
        el:'.app',
        data:{}
    })
</script>

</body>
</html>

字面量方式創建組件

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==


<div class="app">
    <my-com></my-com>
</div>
<script src="../lib/vue-2.4.0.js"></script>
<script>
/*無論是哪種方式創建出來的組件,組件的template屬性指向的模板內容,必須有且只有一個根元素*/
    Vue.component('myCom',{
        template:'<div><h3>這是字面量的方式創建組件</h3><span>只能有一個根元素</span></div>'
    });

    var vm = new Vue({
        el:'.app',
        data:{}
    })
</script>

 傳遞一個標識創建組件


<div class="app">
    <my-com></my-com>
</div>

<!--在被Vue控制的外部寫template模本HTML結構內容-->
<template id="temp">
    <div>
        <h1>這是使用外部標識傳遞給Vue提供的template標籤創建的組件</h1>
        <h4>可以正常的寫HTML代碼了,good!</h4>
    </div>
</template>
<script src="../lib/vue-2.4.0.js"></script>
<script>

    Vue.component('myCom',{
        /*傳遞一個標識*/
        template:'#temp'
    });

    var vm = new Vue({
        el:'.app',
        data:{}
    })
</script>

定義私有組件


<div class="app">
    <login></login>
</div>
<template id="temp">
    <h1>這是一個私有的組件</h1>
</template>
<script src="../lib/vue-2.4.0.js"></script>
<script>
    var vm = new Vue({
        el:'.app',
        data:{},
        methods:{},
        /*定義私有的組件*/
        components:{
            login:{
                template:'#temp'
            }
        }
    })
</script>

 

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章