前端學習之VUE基礎三:組件化開發想法、註冊組件、組件間數據交互

Vue全家桶之組件化開發

一、 組件化開發想法:

1. 組件化思想體現:

  • 標準;
  • 分治;
  • 重用;
  • 組合;

在這裏插入圖片描述

2. 組件化規範: web components

希望:

  • 希望儘可能多的重用代碼;
  • 自定義自檢的方式不太容易;(html css js)
  • 多次使用組件導致衝突

web components 通過創建封裝好功能的定製元素解決上述問題

二、註冊組件:

1. 組件全局註冊:

Vue.component(組件名稱,{
	data: 組件數據;
	template: 組件模板內容
})

注意:

  • 全局組件註冊後,任何vue實例都可以用
  • 組件參數的data值必須是函數同時這個函數要求返回一個對象;
  • 組件模板必須是單個根元素;
  • 組件模板的內容可以是模板字符串;
  • 組件的命名方式:
    • 短橫線(’-’)
    • 駝峯命名: 不能在根組件中使用, 只能在模板字符串中使用;

2. 組件使用:

<div id="app">
    <button-counter></button-counter>
</div>

3. 示例:

在這裏插入圖片描述

<head>
    <title>註冊組件</title>
</head>
<body>
    <div id="app">
        <button-counter></button-counter>
    </div>
     
    <script src="../vue.js"></script>
    <script>
        // 註冊組件
        Vue.component('button-counter', {
            data: function() {
                return {
                    count: 0
                }
            },
            template: "<button @click='count++;'>點擊了{{count}}次</button>"
        })
        var vm = new Vue({
            el: "#app",
            data: {

            }
        })
    </script>
</body>

4. 局部組件註冊:

只能在當前註冊它的vue示例中使用;

<head>
    <title>註冊組件</title>
</head>
<body>
    <div id="app">
        <button-counter></button-counter>

        <!-- 使用局部組件 -->
        <hello-world></hello-world>
        <hello-tom></hello-tom>
    </div>
    
    <script src="../vue.js"></script>
    <script>
        // 註冊組件
        Vue.component('button-counter', {
            data: function() {
                return {
                    count: 0
                }
            },
            template: "<button @click='count++;'>點擊了{{count}}次</button>"
        });
        var HelloWorld = {
            data: function(){
                return {
                msg: 'HelloWorld'
                }
            },
            template: '<div>{{msg}}</div>'
        };
        var HelloTom = {
            data: function() {
                return {
                msg: 'HelloTom'
                }
            },
            template: '<div>{{msg}}</div>'
        };

        var vm = new Vue({
            el: "#app",
            data: {

            },
            components: { 
                // 註冊局部組件
                'hello-world': HelloWorld,
                'hello-tom': HelloTom
            }
        });
    </script>
</body>

三、Vue調試工具:

網址: https://github.com/vuejs/vue-devtools

1. 工具安裝步驟:

  • 克隆倉庫;
  • 安裝依賴包;
npm install
  • 構建;
  • 打開Chrome擴展頁面;
  • 選中開發者模式;
  • 加載已解壓的擴展, 選擇shell/chrome

四、組件間數據交互:

1. 父組件向子組件傳值:

  • 父組件發送的形式是以屬性的形式綁定值到子組件身上;
  • 然後子組件用屬性props接收;
  • 在props中使用駝峯形式,模板中需要使用短橫線的形式字符串形式的模板中沒有這個限制;
Vue.component('menu-item', {
	props: ['title'],
	template: `
		<div>{{title}}</div>`
})
  • 父組件通過屬性將值傳遞給子組件
<menu-item title="來自父組件的屬性"></menu-item>
<menu-item :title="title"></menu-item>
<div id="app">
  <div>{{pmsg}}</div>
   <!--1、menu-item  在 APP中嵌套着 故 menu-item   爲  子組件-->
   <!-- 給子組件傳入一個靜態的值 -->
  <menu-item title='來自父組件的值'></menu-item>
  <!-- 2、 需要動態的數據的時候 需要屬性綁定的形式設置 此時 ptitle  來自父組件data 中的數據 . 
  傳的值可以是數字、對象、數組等等
-->
  <menu-item :title='ptitle' content='hello'></menu-item>
</div>

<script type="text/javascript">
  Vue.component('menu-item', {
    // 3、 子組件用屬性props接收父組件傳遞過來的數據  
    props: ['title', 'content'],
    data: function() {
      return {
        msg: '子組件本身的數據'
      }
    },
    template: '<div>{{msg + "----" + title + "-----" + content}}</div>'
  });
  var vm = new Vue({
    el: '#app',
    data: {
      pmsg: '父組件中內容',
      ptitle: '動態綁定屬性'
    }
  });
</script>

2. props屬性值類型:

  • 字符串: String;
  • 數值: number;
  • 布爾值: boolean
  • 數組: array
  • 對象: object;

3.子組件向父組件傳值:

  • 子組件通過自定義事件向父組件傳遞信息:
<button @click='$emit("enlarge-text")'>擴大字體</button>

$emit() 第一個參數爲 自定義的事件名稱 第二個參數爲需要傳遞的數據;

  • 父組件用v-on 監聽子組件的事件;
<menu-item @enlage-text='fontsize += 0.1;'></menu-item>
 <div id="app">
    <div :style='{fontSize: fontSize + "px"}'>{{pmsg}}</div>
     <!-- 2 父組件用v-on 監聽子組件的事件
		這裏 enlarge-text  是從 $emit 中的第一個參數對應   handle 爲對應的事件處理函數	
	-->	
    <menu-item :parr='parr' @enlarge-text='handle($event)'></menu-item>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      子組件向父組件傳值-攜帶參數
    */
    
    Vue.component('menu-item', {
      props: ['parr'],
      template: `
        <div>
          <ul>
            <li :key='index' v-for='(item,index) in parr'>{{item}}</li>
          </ul>
			###  1、子組件用$emit()觸發事件
			### 第一個參數爲 自定義的事件名稱   第二個參數爲需要傳遞的數據  
          <button @click='$emit("enlarge-text", 5)'>擴大父組件中字體大小</button>
          <button @click='$emit("enlarge-text", 10)'>擴大父組件中字體大小</button>
        </div>
      `
    });
    var vm = new Vue({
      el: '#app',
      data: {
        pmsg: '父組件中內容',
        parr: ['apple','orange','banana'],
        fontSize: 10
      },
      methods: {
        handle: function(val){
          // 擴大字體大小
          this.fontSize += val;
        }
      }
    });
  </script>

4. 兄弟組件之間的傳遞:

4.1 單獨的事件中心管理組件間的通信:

在這裏插入圖片描述

var eventHub = new Vue()

4.2 監聽事件與銷燬事件:

eventHub.$on('add-todo', addTodo)

eventHub.$off('add-todo')

4.3 觸發事件:

eventHub.$emit('add-todo', id)

4.4 實例:

在這裏插入圖片描述

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>兄弟組件傳值</title>
</head>
<body>
    <div id="app">
        <test-tom></test-tom>
        <test-jerry></test-jerry>
    </div>
    <script src="../vue.js"></script>
    <script>
        /* 兄弟組件間傳值 */

        // 事件中心
        var hub = new Vue();

        Vue.component('test-tom', {
            data: function() {
                return {
                    num: 0
                }
            },
            template: `
                <div>
                    <div>Tom: {{num}}</div>
                    <div><button @click='handle'>點擊</button></div>
                </div>
            `,
            methods: {
                handle: function() {
                    // 觸發兄弟組件的事件
                    hub.$emit('jerry-event', 1);
                }
            },
            mounted: function() {
                // 監聽事件
                hub.$on('tom-event', (val) => {
                    this.num += val;
                })
            }
        });
        Vue.component('test-jerry', {
            data: function() {
                return {
                    num: 0
                }
            },
            template: `
                <div>
                    <div>Jerry: {{num}}</div>
                    <div><button @click='handle'>點擊</button></div>
                </div>
            `,
            methods: {
                handle: function() {
                    // 觸發兄弟組件的事件
                    hub.$emit('tom-event', 2);
                }
            },
            mounted: function() {
                // 監聽事件
                hub.$on('jerry-event', (val) => {
                    this.num += val;
                })
            }
        })


        var vm = new Vue({
            el: "#app",
            data: {

            }
        })
    </script>
</body>

5. 組件插槽:

5.1 組件插槽的作用:

父組件系那個子組件傳遞模板內容
在這裏插入圖片描述

5.2 插槽位置:

Vue.component('alert-box', {
	template: `
		<div calss="demo-alert-box">
			<strong>Error!</strong>
		</div>
	`
})

5.3 插槽內容:

<alert-box>someting bad requestd!</alert-box>

6. 具名插槽:

  • 具有名字的插槽
  • 使用 中的 “name” 屬性綁定元素
<head>
    <title>具名插槽</title>
</head>
<body>
    <div id="app">
        <base-layout>
           <!-- 2、 通過slot屬性來指定, 這個slot的值必須和下面slot組件得name值對應上
                    如果沒有匹配到 則放到匿名的插槽中   --> 
          <p slot='header'>標題信息</p>
          <p>主要內容1</p>
          <p>主要內容2</p>
          <p slot='footer'>底部信息信息</p>
        </base-layout>
    
        <base-layout>
          <!-- 注意點:template臨時的包裹標籤最終不會渲染到頁面上     -->  
          <template slot='header'>
            <p>標題信息1</p>
            <p>標題信息2</p>
          </template>
          <p>主要內容1</p>
          <p>主要內容2</p>
          <template slot='footer'>
            <p>底部信息信息1</p>
            <p>底部信息信息2</p>
          </template>
        </base-layout>
      </div>
      <script type="text/javascript" src="../vue.js"></script>
      <script type="text/javascript">
        /*
          具名插槽
        */
        Vue.component('base-layout', {
          template: `
            <div>
              <header>
                ###	1、 使用 <slot> 中的 "name" 屬性綁定元素 指定當前插槽的名字
                <slot name='header'></slot>
              </header>
              <main>
                <slot></slot>
              </main>
              <footer>
                ###  注意點: 
                ###  具名插槽的渲染順序,完全取決於模板,而不是取決於父組件中元素的順序
                <slot name='footer'></slot>
              </footer>
            </div>
          `
        });
        var vm = new Vue({
          el: '#app',
          data: {
            
          }
        });
      </script>
    </body>

7. 作用域插槽:

  • 父組件對子組件加工處理;
  • 既可以複用子組件的slot,又可以使slot內容不一致;

在這裏插入圖片描述

<head>
    <title>作用域插槽</title>
    <style>
        .current {
            color: orange;
        }
    </style>
</head>
<body>
    <div id="app">
        <fruit-list :list='list'>
            <template slot-scope='slotProps'>
                <strong :class="slotProps.info.id == 2?'current': ''">{{slotProps.info.name}}</strong>
            </template>
        </fruit-list>
    </div>
    <script src="../vue.js"></script>
    <script>
        /* 作用域插槽 */
        Vue.component('fruit-list', {
            props: ['list'],
            template: `
                <div>
                    <li :key='item.id' v-for='item in list'>
                        <slot :info='item'>{{item.name}}</slot>
                    </li>
                </div>
            `
        });
        var vm = new Vue({
            el: "#app",
            data: {
                list: [
                    {
                        id:1,
                        name: 'apple'
                    }, {
                        id: 2,
                        name: 'orange'
                    }, {
                        id: 3,
                        name: 'banana'
                    }
                ]
            }
        })
    </script>
</body>

五、案例:購物車:

在這裏插入圖片描述

1. 需求分析:

按照組件化方式實現業務需求:

  • 根據業務功能進行組件化劃分:
    • 標題組件: 展示文本;
    • 列表組件: 列表展示, 商品數量變更, 商品刪除;
    • 結算組件: 計算商品總額;

2. 實現步驟:

功能實現步驟:

  • 實現整體佈局和樣式效果;
  • 劃分獨立的功能組件;
  • 組合所有的子組件形成整體結構;
  • 逐個實現各個組件功能:
    • 標題組件;
    • 列表組件;
    • 結算組件;

3. 代碼實現:

  • 沒有做小於等於0的兼容!!
<head>
    <title>購物車</title>
    <style>
        .container .cart{
            width: 300px;
            margin: auto;
        }
        .container .title {
            background-color: lightblue;
            height: 40px;
            line-height: 40px;
            text-align: center;
        }
        .container .total {
            background-color: #FFCE46;
            height: 50px;
            line-height: 50px;
            text-align: right;
        }
        .container .total button {
            margin: 0 10px;
            background-color: #DC4C40;
            height: 35px;
            width: 80px;
            border: 0;
            color: #fff;
        }
        .container .total span {
            color: red;
            font-weight: bold;
        }
        .container .item {
            height: 55px;
            line-height: 55px;
            position: relative;
            border-top: 1px solid #ADD8E6;
        }
        .container .item img {
            width: 45px;
            height: 45px;
            margin: 5px;
        }
        .container .item .name {
            position: absolute;
            width: 90px;
            top: 0;
            left: 55px;
            font-size: 16px;
        }
        .container .item .change {
            width: 100px;
            position: absolute;
            top: 0;
            right: 50px;
        }
        .container .item .change a {
            font-size: 20px;
            width: 30px;
            text-decoration:none;
            background-color: lightgray;
            vertical-align: middle;
        }
        .container .item .change .num {
            width: 40px;
            height: 25px;
        }
        .container .item .del {
            position: absolute;
            top: 0;
            right: 0px;
            width: 40px;
            text-align: center;
            font-size: 40px;
            cursor: pointer;
            color: red;
        }
        .container .item .del:hover {
            background-color: orange;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="container">
           <my-cart></my-cart>
        </div>
    </div>
    <script src="../../vue.js"></script>
    <script>
        var cartTitle = {
            props: ['uname'],
            template: `
            <div class="title">{{uname}}的商品</div>
            `
        };

        var cartList = {
            props: ['list'],
            template: `
            <div>
                <div class="item" v-for='item in list'>
                    <img :src="item.img"/>
                    <div class="name">{{item.name}}</div>
                    {{item.price}}元
                    <div class="change">
                    <a href="" @click.prevent="sub(item.id)">-</a>
                    <input type="text" class="num" :value="item.num" @blur="changeNum(item.id, $event)"/>
                    <a href=""  @click.prevent="add(item.id)">+</a>
                    </div>
                    <div class="del" @click="del(item.id)">×</div>
                </div>
            </div>
            `,
            methods: {
                sub:function(id) {
                    this.$emit('change-num', {
                        id:id,
                        type: "sub"
                    })
                },
                add: function(id) {
                    this.$emit('change-num', {
                        id:id,
                        type: "add"
                    })
                },
                changeNum: function(id, event) {
                    this.$emit('change-num', {
                        id: id,
                        num: event.target.value,
                        type: "change"
                    });
                },
                del: function(id) {
                    // 把id傳遞給父組件
                    this.$emit('cart-del', id);
                }
            }
        };

        var cartTotal = {
            props: ['list'],
            template: `
            <div class="total">
                <span>總價:{{total}}</span>
                <button>結算</button>
            </div>
            `,
            computed: {
                total: function() {
                    // 計算商品總價
                    var t = 0;
                    this.list.forEach(item => {
                        t += (item.price * item.num);
                    })
                    return t;
                }
            }
        };

        Vue.component('my-cart', {
            data: function() {
                return {
                    uname: '張三',
                    list: [
                        {
                            id: 1,
                            name: "TCL電視",
                            price: 1000,
                            num: 1,
                            img: 'images/a.jpg'
                        },
                        {
                            id: 2,
                            name: "機頂盒",
                            price: 1000,
                            num: 2,
                            img: 'images/b.jpg'
                        },
                        {
                            id: 3,
                            name: "海爾冰箱",
                            price: 1000,
                            num: 3,
                            img: 'images/c.jpg'
                        },
                        {
                            id: 4,
                            name: "小米手機",
                            price: 1000,
                            num: 4,
                            img: 'images/d.jpg'
                        },
                        {
                            id: 5,
                            name: "pptv",
                            price: 1000,
                            num: 5,
                            img: 'images/e.jpg'
                        }
                    ]
                }
            },
            template: `
            <div class='cart'>
                <cart-title :uname='uname'></cart-title>
                <cart-list 
                    :list='list' 
                    @cart-del='delCart($event)' 
                    @change-num=changeNum($event)>
                </cart-list>
                <cart-total :list='list'></cart-total>
            </div>
            `,
            components: {
                'cart-title': cartTitle, 
                'cart-list': cartList,
                'cart-total': cartTotal
            },
            methods: {
                changeNum: function(val) {
                    this.list.some(item => {
                        if (val.type == "add") {
                            if(item.id == val.id) {
                                item.num += 1;
                            }
                        } else if(val.type == "sub"){
                            if(item.id == val.id) {
                                item.num -=1;
                            }
                        } else {
                            if(item.id == val.id) {
                                item.num = val.num;
                            }
                        }
                    })
                },
                delCart:function(id){
                    // 根據id刪除list中對應的數據
                    // 1. 找到id對應的數據
                    var index = this.list.findIndex(item => {
                        return item.id == id;
                    });
                    // 2. 根據索引刪除數據
                    this.list.splice(index, 1);
                },
            }
        })

        var vm = new Vue({
            el: "#app",
            data: {
                
            }
        });

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