iT邦幫忙

1

Vue 之溫習 component 的世界 - 3

props 是從 Vue 實體傳送資料進去元件內,若是元件想要改變 Vue 實體本身的資料,這時候就會需要 emit 了
props 是一個方法,但 emit 是一個事件,即是一個需要被觸發的事件,才會去更改外部的資料

首先建立一個元件跟一個點擊 button 就會觸發 addTotal 的事件:

<div id="app">
  <h2>透過 emit 向外傳遞資訊</h2>
  我透過元件儲值了 {{ cash }} 元
  <button class="btn btn-primary" @click="addTotal">按我</button>
  <hr>
  <button-counter></button-counter>
</div>

<script type="text/x-template" id="button-counter">
  <div>
    <button class="btn btn-outline-primary">增加 {{ counter }} 元</button>
    <input type="number" class="form-control mt-2" v-model="counter">
  </div>
</script>

<script>
    Vue.component('buttonCounter', {
      template: '#button-counter',
      data: function() {
        return {
          counter: 10
        }
      }
    });
    
    var app = new Vue({
      el: '#app',
      data: {
        cash: 300
      },
      methods: {
        addTotal: function(){
          this.cash = this.cash ++ ;
        }
      }
    });
</script>

接著要點擊 button-counter 元件,來觸發 Vue 實體的 addTotal 的事件,並改變 cash 的值:

  1. 首先 x-template 內會有自己的事件
<script type="text/x-template" id="button-counter">
  <div>
    <button @click="incrementCounter" class="btn btn-outline-primary">增加 {{ counter }} 元</button>
    <input type="number" class="form-control mt-2" v-model="counter">
  </div>
</script>
  1. 接著在 Vue.component() 內新增 methods 把 x-template 的事件寫入進去,這就像是在 Vue 實體新增事件 function,只是現在是在元件內新增:
Vue.component('buttonCounter', {
      template: '#button-counter',
      data: function() {
        return {
          counter: 10
        }
      },
      methods: {
          incrementCounter: function(){
          
          }
      }
    });
  1. 接著在元件綁定一個自定義的事件,並指向外部我們要觸發的事件 function:
<div id="app">
  <h2>透過 emit 向外傳遞資訊</h2>
  我透過元件儲值了 {{ cash }} 元
  <button class="btn btn-primary" @click="addTotal">按我</button>
  <hr>
  <!-- add 為自定義的名字 -->
  <button-counter @add="addTotal"></button-counter>
</div>

到這就類似兩邊的橋梁都建好了,接下來只需要連接起來就可以了,所以
4. 在 Vue.component() 內的事件 function 使用 emit 方法,而我們要連結的值,就是在元件內自定義的事件:

Vue.component('buttonCounter', {
      template: '#button-counter',
      data: function() {
        return {
          counter: 10
        }
      },
      methods: {
          incrementCounter: function(){
              this.$emit('add');
          }
      }
    });

這時候我們點擊 button-counter 就可以更改外部的 cash 的值了。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言