Vueday03組件

day03

組件

  • 組件 (Component) 是 Vue.js 最強(qiáng)大的功能之一
  • 組件可以擴(kuò)展 HTML 元素帆疟,封裝可重用的代

組件注冊(cè)

全局注冊(cè)

  • Vue.component('組件名稱', { }) 第1個(gè)參數(shù)是標(biāo)簽名稱证舟,第2個(gè)參數(shù)是一個(gè)選項(xiàng)對(duì)象
  • 全局組件注冊(cè)后屿聋,任何vue實(shí)例都可以用
組件基礎(chǔ)用
<div id="example">
  <!-- 2噪窘、 組件使用 組件名稱 是以HTML標(biāo)簽的形式使用  -->  
  <my-component></my-component>
</div>
<script>
    //   注冊(cè)組件 
    // 1片吊、 my-component 就是組件中自定義的標(biāo)簽名
    Vue.component('my-component', {
      template: '<div>A custom component!</div>'
    })

    // 創(chuàng)建根實(shí)例
    new Vue({
      el: '#example'
    })

</script>
組件注意事項(xiàng)
  • 組件參數(shù)的data值必須是函數(shù)同時(shí)這個(gè)函數(shù)要求返回一個(gè)對(duì)象
  • 組件模板必須是單個(gè)根元素
  • 組件模板的內(nèi)容可以是模板字符串
  <div id="app">
     <!-- 
        4、  組件可以重復(fù)使用多次 
          因?yàn)閐ata中返回的是一個(gè)對(duì)象所以每個(gè)組件中的數(shù)據(jù)是私有的
          即每個(gè)實(shí)例可以維護(hù)一份被返回對(duì)象的獨(dú)立的拷貝   
    --> 
    <button-counter></button-counter>
    <button-counter></button-counter>
    <button-counter></button-counter>
      <!-- 8盖灸、必須使用短橫線的方式使用組件 -->
     <hello-world></hello-world>
  </div>

<script type="text/javascript">
    //5  如果使用駝峰式命名組件酬诀,那么在使用組件的時(shí)候,只能在字符串模板中用駝峰的方式使用組件婴噩,
    // 7擎场、但是在普通的標(biāo)簽?zāi)0逯杏鸬拢仨毷褂枚虣M線的方式使用組件
     Vue.component('HelloWorld', {
      data: function(){
        return {
          msg: 'HelloWorld'
        }
      },
      template: '<div>{{msg}}</div>'
    });
    
    
    
    Vue.component('button-counter', {
      // 1、組件參數(shù)的data值必須是函數(shù) 
      // 同時(shí)這個(gè)函數(shù)要求返回一個(gè)對(duì)象  
      data: function(){
        return {
          count: 0
        }
      },
      //  2迅办、組件模板必須是單個(gè)根元素
      //  3宅静、組件模板的內(nèi)容可以是模板字符串  
      template: `
        <div>
          <button @click="handle">點(diǎn)擊了{(lán){count}}次</button>
          <button>測(cè)試123</button>
            #  6 在字符串模板中可以使用駝峰的方式使用組件   
           <HelloWorld></HelloWorld>
        </div>
      `,
      methods: {
        handle: function(){
          this.count += 2;
        }
      }
    })
    var vm = new Vue({
      el: '#app',
      data: {
        
      }
    });
  </script>

局部注冊(cè)

  • 只能在當(dāng)前注冊(cè)它的vue實(shí)例中使用
  <div id="app">
      <my-component></my-component>
  </div>


<script>
    // 定義組件的模板
    var Child = {
      template: '<div>A custom component!</div>'
    }
    new Vue({
      //局部注冊(cè)組件  
      components: {
        // <my-component> 將只在父模板可用  一定要在實(shí)例上注冊(cè)了才能在html文件中使用
        'my-component': Child
      }
    })
 </script>

Vue 調(diào)試工具

Vue組件之間傳值

父組件向子組件傳值

  • 父組件發(fā)送的形式是以屬性的形式綁定值到子組件身上。
  • 然后子組件用屬性props接收
  • 在props中使用駝峰形式站欺,模板中需要使用短橫線的形式字符串形式的模板中沒有這個(gè)限制
  <div id="app">
    <div>{{pmsg}}</div>
     <!--1姨夹、menu-item  在 APP中嵌套著 故 menu-item   為  子組件      -->
     <!-- 給子組件傳入一個(gè)靜態(tài)的值 -->
    <menu-item title='來自父組件的值'></menu-item>
    <!-- 2、 需要?jiǎng)討B(tài)的數(shù)據(jù)的時(shí)候 需要屬性綁定的形式設(shè)置 此時(shí) ptitle  來自父組件data 中的數(shù)據(jù) . 
          傳的值可以是數(shù)字矾策、對(duì)象磷账、數(shù)組等等
    -->
    <menu-item :title='ptitle' content='hello'></menu-item>
  </div>

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

子組件向父組件傳值

  • 子組件用$emit()觸發(fā)事件
  • $emit() 第一個(gè)參數(shù)為 自定義的事件名稱 第二個(gè)參數(shù)為需要傳遞的數(shù)據(jù)
  • 父組件用v-on 監(jiān)聽子組件的事件

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

兄弟之間的傳遞

  • 兄弟之間傳遞數(shù)據(jù)需要借助于事件中心逃糟,通過事件中心傳遞數(shù)據(jù)
    • 提供事件中心 var hub = new Vue()
  • 傳遞數(shù)據(jù)方,通過一個(gè)事件觸發(fā)hub.$emit(方法名蓬豁,傳遞的數(shù)據(jù))
  • 接收數(shù)據(jù)方绰咽,通過mounted(){} 鉤子中 觸發(fā)hub.$on()方法名
  • 銷毀事件 通過hub.$off()方法名銷毀之后無法進(jìn)行傳遞數(shù)據(jù)
 <div id="app">
    <div>父組件</div>
    <div>
      <button @click='handle'>銷毀事件</button>
    </div>
    <test-tom></test-tom>
    <test-jerry></test-jerry>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      兄弟組件之間數(shù)據(jù)傳遞
    */
    //1、 提供事件中心
    var hub = new Vue();

    Vue.component('test-tom', {
      data: function(){
        return {
          num: 0
        }
      },
      template: `
        <div>
          <div>TOM:{{num}}</div>
          <div>
            <button @click='handle'>點(diǎn)擊</button>
          </div>
        </div>
      `,
      methods: {
        handle: function(){
          //2地粪、傳遞數(shù)據(jù)方取募,通過一個(gè)事件觸發(fā)hub.$emit(方法名,傳遞的數(shù)據(jù))   觸發(fā)兄弟組件的事件
          hub.$emit('jerry-event', 2);
        }
      },
      mounted: function() {
       // 3蟆技、接收數(shù)據(jù)方玩敏,通過mounted(){} 鉤子中  觸發(fā)hub.$on(方法名
        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'>點(diǎn)擊</button>
          </div>
        </div>
      `,
      methods: {
        handle: function(){
          //2、傳遞數(shù)據(jù)方付魔,通過一個(gè)事件觸發(fā)hub.$emit(方法名,傳遞的數(shù)據(jù))   觸發(fā)兄弟組件的事件
          hub.$emit('tom-event', 1);
        }
      },
      mounted: function() {
        // 3飞蹂、接收數(shù)據(jù)方几苍,通過mounted(){} 鉤子中  觸發(fā)hub.$on()方法名
        hub.$on('jerry-event', (val) => {
          this.num += val;
        });
      }
    });
    var vm = new Vue({
      el: '#app',
      data: {
        
      },
      methods: {
        handle: function(){
          //4、銷毀事件 通過hub.$off()方法名銷毀之后無法進(jìn)行傳遞數(shù)據(jù)  
          hub.$off('tom-event');
          hub.$off('jerry-event');
        }
      }
    });
  </script>

組件插槽

  • 組件的最大特性就是復(fù)用性陈哑,而用好插槽能大大提高組件的可復(fù)用能力

匿名插槽


  <div id="app">
    <!-- 這里的所有組件標(biāo)簽中嵌套的內(nèi)容會(huì)替換掉slot  如果不傳值 則使用 slot 中的默認(rèn)值  -->  
    <alert-box>有bug發(fā)生</alert-box>
    <alert-box>有一個(gè)警告</alert-box>
    <alert-box></alert-box>
  </div>

  <script type="text/javascript">
    /*
      組件插槽:父組件向子組件傳遞內(nèi)容
    */
    Vue.component('alert-box', {
      template: `
        <div>
          <strong>ERROR:</strong>
        # 當(dāng)組件渲染的時(shí)候妻坝,這個(gè) <slot> 元素將會(huì)被替換為“組件標(biāo)簽中嵌套的內(nèi)容”。
        # 插槽內(nèi)可以包含任何模板代碼惊窖,包括 HTML
          <slot>默認(rèn)內(nèi)容</slot>
        </div>
      `
    });
    var vm = new Vue({
      el: '#app',
      data: {
        
      }
    });
  </script>
</body>
</html>

具名插槽

  • 具有名字的插槽
  • 使用 <slot> 中的 "name" 屬性綁定元素

  <div id="app">
    <base-layout>
       <!-- 2刽宪、 通過slot屬性來指定, 這個(gè)slot的值必須和下面slot組件得name值對(duì)應(yīng)上
                如果沒有匹配到 則放到匿名的插槽中   --> 
      <p slot='header'>標(biāo)題信息</p>
      <p>主要內(nèi)容1</p>
      <p>主要內(nèi)容2</p>
      <p slot='footer'>底部信息信息</p>
    </base-layout>

    <base-layout>
      <!-- 注意點(diǎn):template臨時(shí)的包裹標(biāo)簽最終不會(huì)渲染到頁面上     -->  
      <template slot='header'>
        <p>標(biāo)題信息1</p>
        <p>標(biāo)題信息2</p>
      </template>
      <p>主要內(nèi)容1</p>
      <p>主要內(nèi)容2</p>
      <template slot='footer'>
        <p>底部信息信息1</p>
        <p>底部信息信息2</p>
      </template>
    </base-layout>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      具名插槽
    */
    Vue.component('base-layout', {
      template: `
        <div>
          <header>
            ### 1、 使用 <slot> 中的 "name" 屬性綁定元素 指定當(dāng)前插槽的名字
            <slot name='header'></slot>
          </header>
          <main>
            <slot></slot>
          </main>
          <footer>
            ###  注意點(diǎn): 
            ###  具名插槽的渲染順序界酒,完全取決于模板圣拄,而不是取決于父組件中元素的順序
            <slot name='footer'></slot>
          </footer>
        </div>
      `
    });
    var vm = new Vue({
      el: '#app',
      data: {
        
      }
    });
  </script>
</body>
</html>

作用域插槽

  • 父組件對(duì)子組件加工處理
  • 既可以復(fù)用子組件的slot,又可以使slot內(nèi)容不一致
  <div id="app">
    <!-- 
        1毁欣、當(dāng)我們希望li 的樣式由外部使用組件的地方定義庇谆,因?yàn)榭赡苡卸喾N地方要使用該組件岳掐,
        但樣式希望不一樣 這個(gè)時(shí)候我們需要使用作用域插槽 
        
    -->  
    <fruit-list :list='list'>
       <!-- 2、 父組件中使用了<template>元素,而且包含scope="slotProps",
            slotProps在這里只是臨時(shí)變量   
        --->    
      <template slot-scope='slotProps'>
        <strong v-if='slotProps.info.id==3' class="current">
            {{slotProps.info.name}}              
         </strong>
        <span v-else>{{slotProps.info.name}}</span>
      </template>
    </fruit-list>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      作用域插槽
    */
    Vue.component('fruit-list', {
      props: ['list'],
      template: `
        <div>
          <li :key='item.id' v-for='item in list'>
            ###  3饭耳、 在子組件模板中,<slot>元素上有一個(gè)類似props傳遞數(shù)據(jù)給組件的寫法msg="xxx",
            ###   插槽可以提供一個(gè)默認(rèn)內(nèi)容串述,如果如果父組件沒有為這個(gè)插槽提供了內(nèi)容,會(huì)顯示默認(rèn)的內(nèi)容寞肖。
                    如果父組件為這個(gè)插槽提供了內(nèi)容纲酗,則默認(rèn)的內(nèi)容會(huì)被替換掉
            <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>
</html>

購物車案例

1. 實(shí)現(xiàn)組件化布局

  • 把靜態(tài)頁面轉(zhuǎn)換成組件化模式
  • 把組件渲染到頁面上
 <div id="app">
    <div class="container">
      <!-- 2、把組件渲染到頁面上 --> 
      <my-cart></my-cart>
    </div>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    # 1新蟆、 把靜態(tài)頁面轉(zhuǎn)換成組件化模式
    # 1.1  標(biāo)題組件 
    var CartTitle = {
      template: `
        <div class="title">我的商品</div>
      `
    }
    # 1.2  商品列表組件 
    var CartList = {
      #  注意點(diǎn) :  組件模板必須是單個(gè)根元素  
      template: `
        <div>
          <div class="item">
            <img src="img/a.jpg"/>
            <div class="name"></div>
            <div class="change">
              <a href="">-</a>
              <input type="text" class="num" />
              <a href="">+</a>
            </div>
            <div class="del">×</div>
          </div>
          <div class="item">
            <img src="img/b.jpg"/>
            <div class="name"></div>
            <div class="change">
              <a href="">-</a>
              <input type="text" class="num" />
              <a href="">+</a>
            </div>
            <div class="del">×</div>
          </div>
          <div class="item">
            <img src="img/c.jpg"/>
            <div class="name"></div>
            <div class="change">
              <a href="">-</a>
              <input type="text" class="num" />
              <a href="">+</a>
            </div>
            <div class="del">×</div>
          </div>
          <div class="item">
            <img src="img/d.jpg"/>
            <div class="name"></div>
            <div class="change">
              <a href="">-</a>
              <input type="text" class="num" />
              <a href="">+</a>
            </div>
            <div class="del">×</div>
          </div>
          <div class="item">
            <img src="img/e.jpg"/>
            <div class="name"></div>
            <div class="change">
              <a href="">-</a>
              <input type="text" class="num" />
              <a href="">+</a>
            </div>
            <div class="del">×</div>
          </div>
        </div>
      `
    }
    # 1.3  商品結(jié)算組件 
    var CartTotal = {
      template: `
        <div class="total">
          <span>總價(jià):123</span>
          <button>結(jié)算</button>
        </div>
      `
    }
    ## 1.4  定義一個(gè)全局組件 my-cart
    Vue.component('my-cart',{
      ##  1.6 引入子組件  
      template: `
        <div class='cart'>
          <cart-title></cart-title>
          <cart-list></cart-list>
          <cart-total></cart-total>
        </div>
      `,
      # 1.5  注冊(cè)子組件   
      components: {
        'cart-title': CartTitle,
        'cart-list': CartList,
        'cart-total': CartTotal
      }
    });
    var vm = new Vue({
      el: '#app',
      data: {

      }
    });

  </script>



2觅赊、實(shí)現(xiàn) 標(biāo)題和結(jié)算功能組件

  • 標(biāo)題組件實(shí)現(xiàn)動(dòng)態(tài)渲染
    • 從父組件把標(biāo)題數(shù)據(jù)傳遞過來 即 父向子組件傳值
    • 把傳遞過來的數(shù)據(jù)渲染到頁面上
  • 結(jié)算功能組件
    • 從父組件把商品列表list 數(shù)據(jù)傳遞過來 即 父向子組件傳值
    • 把傳遞過來的數(shù)據(jù)計(jì)算最終價(jià)格渲染到頁面上
 <div id="app">
    <div class="container">
      <my-cart></my-cart>
    </div>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
     # 2.2  標(biāo)題組件     子組件通過props形式接收父組件傳遞過來的uname數(shù)據(jù)
    var CartTitle = {
      props: ['uname'],
      template: `
        <div class="title">{{uname}}的商品</div>
      `
    }
    # 2.3  商品結(jié)算組件  子組件通過props形式接收父組件傳遞過來的list數(shù)據(jù)   
    var CartTotal = {
      props: ['list'],
      template: `
        <div class="total">
          <span>總價(jià):{{total}}</span>
          <button>結(jié)算</button>
        </div>
      `,
      computed: {
        # 2.4    計(jì)算商品的總價(jià)  并渲染到頁面上 
        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: 'img/a.jpg'
          },{
            id: 2,
            name: '機(jī)頂盒',
            price: 1000,
            num: 1,
            img: 'img/b.jpg'
          },{
            id: 3,
            name: '海爾冰箱',
            price: 1000,
            num: 1,
            img: 'img/c.jpg'
          },{
            id: 4,
            name: '小米手機(jī)',
            price: 1000,
            num: 1,
            img: 'img/d.jpg'
          },{
            id: 5,
            name: 'PPTV電視',
            price: 1000,
            num: 2,
            img: 'img/e.jpg'
          }]
        }
      },
      #  2.1  父組件向子組件以屬性傳遞的形式 傳遞數(shù)據(jù)
      #   向 標(biāo)題組件傳遞 uname 屬性   向 商品結(jié)算組件傳遞 list  屬性  
      template: `
        <div class='cart'>
          <cart-title :uname='uname'></cart-title>
          <cart-list></cart-list>
          <cart-total :list='list'></cart-total>
        </div>
      `,
      components: {
        'cart-title': CartTitle,
        'cart-list': CartList,
        'cart-total': CartTotal
      }
    });
    var vm = new Vue({
      el: '#app',
      data: {

      }
    });

  </script>

3. 實(shí)現(xiàn)列表組件刪除功能

  • 從父組件把商品列表list 數(shù)據(jù)傳遞過來 即 父向子組件傳值
  • 把傳遞過來的數(shù)據(jù)渲染到頁面上
  • 點(diǎn)擊刪除按鈕的時(shí)候刪除對(duì)應(yīng)的數(shù)據(jù)
    • 給按鈕添加點(diǎn)擊事件把需要?jiǎng)h除的id傳遞過來
      • 子組件中不推薦操作父組件的數(shù)據(jù)有可能多個(gè)子組件使用父組件的數(shù)據(jù) 我們需要把數(shù)據(jù)傳遞給父組件讓父組件操作數(shù)據(jù)
      • 父組件刪除對(duì)應(yīng)的數(shù)據(jù)
 <div id="app">
    <div class="container">
      <my-cart></my-cart>
    </div>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    
    var CartTitle = {
      props: ['uname'],
      template: `
        <div class="title">{{uname}}的商品</div>
      `
    }
    #  3.2 把列表數(shù)據(jù)動(dòng)態(tài)渲染到頁面上  
    var CartList = {
      props: ['list'],
      template: `
        <div>
          <div :key='item.id' v-for='item in list' class="item">
            <img :src="item.img"/>
            <div class="name">{{item.name}}</div>
            <div class="change">
              <a href="">-</a>
              <input type="text" class="num" />
              <a href="">+</a>
            </div>
            # 3.3  給按鈕添加點(diǎn)擊事件把需要?jiǎng)h除的id傳遞過來
            <div class="del" @click='del(item.id)'>×</div>
          </div>
        </div>
      `,
      methods: {
        del: function(id){
           # 3.4 子組件中不推薦操作父組件的數(shù)據(jù)有可能多個(gè)子組件使用父組件的數(shù)據(jù) 
          #       我們需要把數(shù)據(jù)傳遞給父組件 讓父組件操作數(shù)據(jù) 
          this.$emit('cart-del', id);
        }
      }
    }
    var CartTotal = {
      props: ['list'],
      template: `
        <div class="total">
          <span>總價(jià):{{total}}</span>
          <button>結(jié)算</button>
        </div>
      `,
      computed: {
        total: function() {
          // 計(jì)算商品的總價(jià)
          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: 'img/a.jpg'
          },{
            id: 2,
            name: '機(jī)頂盒',
            price: 1000,
            num: 1,
            img: 'img/b.jpg'
          },{
            id: 3,
            name: '海爾冰箱',
            price: 1000,
            num: 1,
            img: 'img/c.jpg'
          },{
            id: 4,
            name: '小米手機(jī)',
            price: 1000,
            num: 1,
            img: 'img/d.jpg'
          },{
            id: 5,
            name: 'PPTV電視',
            price: 1000,
            num: 2,
            img: 'img/e.jpg'
          }]
        }
      },
      # 3.1 從父組件把商品列表list 數(shù)據(jù)傳遞過來 即 父向子組件傳值  
      template: `
        <div class='cart'>
          <cart-title :uname='uname'></cart-title>
          #  3.5  父組件通過事件綁定 接收子組件傳遞過來的數(shù)據(jù) 
          <cart-list :list='list' @cart-del='delCart($event)'></cart-list>
          <cart-total :list='list'></cart-total>
        </div>
      `,
      components: {
        'cart-title': CartTitle,
        'cart-list': CartList,
        'cart-total': CartTotal
      },
      methods: {
        # 3.6    根據(jù)id刪除list中對(duì)應(yīng)的數(shù)據(jù)        
        delCart: function(id) {
          // 1、找到id所對(duì)應(yīng)數(shù)據(jù)的索引
          var index = this.list.findIndex(item=>{
            return item.id == id;
          });
          // 2栅葡、根據(jù)索引刪除對(duì)應(yīng)數(shù)據(jù)
          this.list.splice(index, 1);
        }
      }
    });
    var vm = new Vue({
      el: '#app',
      data: {

      }
    });

  </script>
</body>
</html>

4. 實(shí)現(xiàn)組件更新數(shù)據(jù)功能 上

  • 將輸入框中的默認(rèn)數(shù)據(jù)動(dòng)態(tài)渲染出來
  • 輸入框失去焦點(diǎn)的時(shí)候 更改商品的數(shù)量
  • 子組件中不推薦操作數(shù)據(jù) 把這些數(shù)據(jù)傳遞給父組件 讓父組件處理這些數(shù)據(jù)
  • 父組件中接收子組件傳遞過來的數(shù)據(jù)并處理 
    
 <div id="app">
    <div class="container">
      <my-cart></my-cart>
    </div>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    
    var CartTitle = {
      props: ['uname'],
      template: `
        <div class="title">{{uname}}的商品</div>
      `
    }
    var CartList = {
      props: ['list'],
      template: `
        <div>
          <div :key='item.id' v-for='item in list' class="item">
            <img :src="item.img"/>
            <div class="name">{{item.name}}</div>
            <div class="change">
              <a href="">-</a>
                # 1. 將輸入框中的默認(rèn)數(shù)據(jù)動(dòng)態(tài)渲染出來
                # 2. 輸入框失去焦點(diǎn)的時(shí)候 更改商品的數(shù)量  需要將當(dāng)前商品的id 傳遞過來
              <input type="text" class="num" :value='item.num' @blur='changeNum(item.id, $event)'/>
              <a href="">+</a>
            </div>
            <div class="del" @click='del(item.id)'>×</div>
          </div>
        </div>
      `,
      methods: {
        changeNum: function(id, event){
          # 3 子組件中不推薦操作數(shù)據(jù)  因?yàn)閯e的組件可能也引用了這些數(shù)據(jù)
          #  把這些數(shù)據(jù)傳遞給父組件 讓父組件處理這些數(shù)據(jù)
          this.$emit('change-num', {
            id: id,
            num: event.target.value
          });
        },
        del: function(id){
          // 把id傳遞給父組件
          this.$emit('cart-del', id);
        }
      }
    }
    var CartTotal = {
      props: ['list'],
      template: `
        <div class="total">
          <span>總價(jià):{{total}}</span>
          <button>結(jié)算</button>
        </div>
      `,
      computed: {
        total: function() {
          // 計(jì)算商品的總價(jià)
          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: 'img/a.jpg'
          }]
      },
      template: `
        <div class='cart'>
          <cart-title :uname='uname'></cart-title>
            # 4  父組件中接收子組件傳遞過來的數(shù)據(jù) 
          <cart-list :list='list' @change-num='changeNum($event)' @cart-del='delCart($event)'></cart-list>
          <cart-total :list='list'></cart-total>
        </div>
      `,
      components: {
        'cart-title': CartTitle,
        'cart-list': CartList,
        'cart-total': CartTotal
      },
      methods: {
        changeNum: function(val) {
          //4.1 根據(jù)子組件傳遞過來的數(shù)據(jù)茉兰,跟新list中對(duì)應(yīng)的數(shù)據(jù)
          this.list.some(item=>{
            if(item.id == val.id) {
              item.num = val.num;
              // 終止遍歷
              return true;
            }
          });
        },
        delCart: function(id) {
          // 根據(jù)id刪除list中對(duì)應(yīng)的數(shù)據(jù)
          // 1、找到id所對(duì)應(yīng)數(shù)據(jù)的索引
          var index = this.list.findIndex(item=>{
            return item.id == id;
          });
          // 2欣簇、根據(jù)索引刪除對(duì)應(yīng)數(shù)據(jù)
          this.list.splice(index, 1);
        }
      }
    });
    var vm = new Vue({
      el: '#app',
      data: {

      }
    });

  </script>

5. 實(shí)現(xiàn)組件更新數(shù)據(jù)功能 下

  • 子組件通過一個(gè)標(biāo)識(shí)符來標(biāo)記對(duì)用的用戶點(diǎn)擊 + - 或者輸入框輸入的內(nèi)容
  • 父組件拿到標(biāo)識(shí)符更新對(duì)應(yīng)的組件
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    .container {
    }
    .container .cart {
      width: 300px;
      margin: auto;
    }
    .container .title {
      background-color: lightblue;
      height: 40px;
      line-height: 40px;
      text-align: center;
      /*color: #fff;*/  
    }
    .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;
    }
    .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 type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    
    var CartTitle = {
      props: ['uname'],
      template: `
        <div class="title">{{uname}}的商品</div>
      `
    }
    var CartList = {
      props: ['list'],
      template: `
        <div>
          <div :key='item.id' v-for='item in list' class="item">
            <img :src="item.img"/>
            <div class="name">{{item.name}}</div>
            <div class="change">
              # 1.  + - 按鈕綁定事件 
              <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: {
        changeNum: function(id, event){
          this.$emit('change-num', {
            id: id,
            type: 'change',
            num: event.target.value
          });
        },
        sub: function(id){
          # 2 數(shù)量的增加和減少通過父組件來計(jì)算   每次都是加1 和 減1 不需要傳遞數(shù)量   父組件需要一個(gè)類型來判斷 是 加一 還是減1  以及是輸入框輸入的數(shù)據(jù)  我們通過type 標(biāo)識(shí)符來標(biāo)記 不同的操作   
          this.$emit('change-num', {
            id: id,
            type: 'sub'
          });
        },
        add: function(id){
         # 2 數(shù)量的增加和減少通過父組件來計(jì)算   每次都是加1 和 減1 不需要傳遞數(shù)量   父組件需要一個(gè)類型來判斷 是 加一 還是減1  以及是輸入框輸入的數(shù)據(jù)  我們通過type 標(biāo)識(shí)符來標(biāo)記 不同的操作
          this.$emit('change-num', {
            id: id,
            type: 'add'
          });
        },
        del: function(id){
          // 把id傳遞給父組件
          this.$emit('cart-del', id);
        }
      }
    }
    var CartTotal = {
      props: ['list'],
      template: `
        <div class="total">
          <span>總價(jià):{{total}}</span>
          <button>結(jié)算</button>
        </div>
      `,
      computed: {
        total: function() {
          // 計(jì)算商品的總價(jià)
          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: 'img/a.jpg'
          },{
            id: 2,
            name: '機(jī)頂盒',
            price: 1000,
            num: 1,
            img: 'img/b.jpg'
          },{
            id: 3,
            name: '海爾冰箱',
            price: 1000,
            num: 1,
            img: 'img/c.jpg'
          },{
            id: 4,
            name: '小米手機(jī)',
            price: 1000,
            num: 1,
            img: 'img/d.jpg'
          },{
            id: 5,
            name: 'PPTV電視',
            price: 1000,
            num: 2,
            img: 'img/e.jpg'
          }]
        }
      },
      template: `
        <div class='cart'>
          <cart-title :uname='uname'></cart-title>  
        # 3 父組件通過事件監(jiān)聽   接收子組件的數(shù)據(jù)  
          <cart-list :list='list' @change-num='changeNum($event)' @cart-del='delCart($event)'></cart-list>
          <cart-total :list='list'></cart-total>
        </div>
      `,
      components: {
        'cart-title': CartTitle,
        'cart-list': CartList,
        'cart-total': CartTotal
      },
      methods: {
        changeNum: function(val) {
          #4 分為三種情況:輸入框變更规脸、加號(hào)變更、減號(hào)變更
          if(val.type=='change') {
            // 根據(jù)子組件傳遞過來的數(shù)據(jù)熊咽,跟新list中對(duì)應(yīng)的數(shù)據(jù)
            this.list.some(item=>{
              if(item.id == val.id) {
                item.num = val.num;
                // 終止遍歷
                return true;
              }
            });
          }else if(val.type=='sub'){
            // 減一操作
            this.list.some(item=>{
              if(item.id == val.id) {
                item.num -= 1;
                // 終止遍歷
                return true;
              }
            });
          }else if(val.type=='add'){
            // 加一操作
            this.list.some(item=>{
              if(item.id == val.id) {
                item.num += 1;
                // 終止遍歷
                return true;
              }
            });
          }
        }
      }
    });
    var vm = new Vue({
      el: '#app',
      data: {

      }
    });

  </script>
</body>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末莫鸭,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子横殴,更是在濱河造成了極大的恐慌被因,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,084評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件衫仑,死亡現(xiàn)場(chǎng)離奇詭異梨与,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)文狱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門粥鞋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人瞄崇,你說我怎么就攤上這事呻粹。” “怎么了苏研?”我有些...
    開封第一講書人閱讀 163,450評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵等浊,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我摹蘑,道長(zhǎng)筹燕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,322評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮庄萎,結(jié)果婚禮上踪少,老公的妹妹穿的比我還像新娘。我一直安慰自己糠涛,他們只是感情好援奢,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評(píng)論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著忍捡,像睡著了一般集漾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上砸脊,一...
    開封第一講書人閱讀 51,274評(píng)論 1 300
  • 那天具篇,我揣著相機(jī)與錄音,去河邊找鬼凌埂。 笑死驱显,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的瞳抓。 我是一名探鬼主播埃疫,決...
    沈念sama閱讀 40,126評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼孩哑!你這毒婦竟也來了栓霜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,980評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤横蜒,失蹤者是張志新(化名)和其女友劉穎胳蛮,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體丛晌,經(jīng)...
    沈念sama閱讀 45,414評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡仅炊,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了澎蛛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抚垄。...
    茶點(diǎn)故事閱讀 39,773評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖瓶竭,靈堂內(nèi)的尸體忽然破棺而出督勺,到底是詐尸還是另有隱情渠羞,我是刑警寧澤斤贰,帶...
    沈念sama閱讀 35,470評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站次询,受9級(jí)特大地震影響荧恍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評(píng)論 3 327
  • 文/蒙蒙 一送巡、第九天 我趴在偏房一處隱蔽的房頂上張望摹菠。 院中可真熱鬧,春花似錦骗爆、人聲如沸次氨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽煮寡。三九已至,卻和暖如春犀呼,著一層夾襖步出監(jiān)牢的瞬間幸撕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工外臂, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留坐儿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,865評(píng)論 2 370
  • 正文 我出身青樓宋光,卻偏偏與公主長(zhǎng)得像貌矿,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子跃须,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 什么是組件站叼? 組件 (Component) 是 Vue.js 最強(qiáng)大的功能之一。組件可以擴(kuò)展 HTML 元素菇民,封裝...
    youins閱讀 9,480評(píng)論 0 13
  • 【2019-3-4更新】Vue 2.6+修改了部分語法尽楔,對(duì)插槽的使用有了較多的更新。在本文中筆者在相應(yīng)位置給出了更...
    果汁涼茶丶閱讀 10,244評(píng)論 2 36
  • 此文基于官方文檔第练,里面部分例子有改動(dòng)阔馋,加上了一些自己的理解 什么是組件? 組件(Component)是 Vue.j...
    陸志均閱讀 3,825評(píng)論 5 14
  • 長(zhǎng)大的感覺恐怕就是,你開始對(duì)那些出自于名人名言或者俗語諺語的話語有了更深刻的領(lǐng)悟吧婴梧。 最近一段時(shí)間下梢,一直在不停的筆...
    圍棋小貓閱讀 608評(píng)論 0 0
  • 版權(quán)聲明:本文源自簡(jiǎn)書【九昍】,歡迎轉(zhuǎn)載塞蹭,轉(zhuǎn)載請(qǐng)務(wù)必注明出處: http://www.reibang.com/p/...
    九昍閱讀 480評(píng)論 0 3