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

  <script type="text/x-template" id="buttonCounter">
    <div>
    <button @click="incrementCounter" class="btn btn-outline-primary">增加 {{ counter }} 元</button>
    <input type="number" class="form-control mt-2" v-model="counter">
  </div>`
</script>
#app{
  width: 400px;
}
View Compiled
Vue.component("buttonCounter", {
  template: `#buttonCounter`,
  data: function () {
    return {
      counter: 1
    };
  },
  methods: {
    incrementCounter() {
      this.$emit("increment", Number(this.counter));
    }
  }
});
// 物件實體
var app = new Vue({
  el: "#app",
  data: {
    cash: 300
  },
  methods: {
    incrementTotal(newNumber) {
      this.cash = this.cash + newNumber;
    }
  }
});

External CSS

  1. https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js