手把手教你VUE從入門到放棄—— 篇四(組件化思想,全局組件及局部組件)

所謂組件化思想,顧名思義就是化繁爲簡,把一個整體拆成多個模塊,一個模塊爲一個組件來實現。

全局組件:使用Vue.component("組件名",{
            props:['屬性名'],  
            template:'html模板'
        }
);

如下圖

源碼如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全局組件</title>
      <script src="vue.js"></script>
</head>
<body>
    <div id = 'app2'>
        <input type='text' v-model='inputVal'/>
        <button @click='addToList'>提交</button>
        <ul >
            <todo-item v-bind:con1="item" v-for="item in list"></todo-item>
        </ul>
    </div>
    <script>
        Vue.component("TodoItem",{
            props:['con1'],
            template:'<li>{{con1}}</li>'
        });
        var app = new Vue({
            el:'#app2',
            data:{
                list:[],
                inputVal : ''
             },
             methods:{
                 addToList:function(){
                     this.$data.list.push(this.inputVal);
                     this.inputVal = '';
                 }
             }
        });
    </script>
</body>


</html>

 局部組件,如下圖,對比上面全局組件看看啥差別,個人喜歡用全局組件

源碼如下 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>局部組件</title>
      <script src="vue.js"></script>
</head>
<body>
    <div id = 'app2'>
        <input type='text' v-model='inputVal'/>
        <button @click='addToList'>提交</button>
        <ul >
            <com v-bind:con1="item" v-for="item in list"></com>
        </ul>
    </div>
    <script>
        var com = {
            props:['con1'],
            template:'<li>{{con1}}</li>'
        };
        var app = new Vue({
            el:'#app2',
            data:{
                list:[],
                inputVal : ''
             },
             components:{
                 com:com
             },
             methods:{
                 addToList:function(){
                     this.$data.list.push(this.inputVal);
                     this.inputVal = '';
                 }
             }
        });
    </script>
</body>


</html>

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