1. 程式人生 > 實用技巧 >父子元件一次通訊的案例

父子元件一次通訊的案例

<!DOCTYPE html>
<!--suppress ALL -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <!-- 需求: 讓父元件和子元件裡面的num隨著input輸入一起變 -->
  <!-- 也就是先父元件傳到子元件,然後子元件再傳到父元件 -->
  <div id="app">
    <!-- 注意這裡的兩次繫結 -->
    <cpn :number1="num1" @num1change="num1change"></cpn>
  </div>

  <template id="cpn">
    <div>
      <h2>父元件(全域性元件):{{number1}}</h2>
      <h2>子元件(區域性元件):{{dnumber1}}</h2>
      <!-- 將子元件的屬性和這裡input雙向繫結 -->
      <input type="text" :value="dnumber1" @input="num1Input">
    </div>
  </template>

  <script src="../vue.js"></script>
  <script>
    const app = new Vue({
      // 父元件
      el: '#app',
      data: {
        num1:1,
        num2:0
      },
      methods: {
        // 這裡是讓父元件的num改變的事件
        num1change(value){
          this.num1 = parseFloat(value),
        }
      },
      components:{
        // 子元件
        cpn:{
          template: '#cpn',
          // 確認傳遞過來的型別
          props: {
            number1:Number,
          },
          // 這裡用data儲存父元件傳過來的資料
          data(){
            return { 
              dnumber1: this.number1,
            }
          },
          methods: {
            num1Input(event){
              // 將input中value賦值到的dnumber1中
              this.dnumber1 = event.target.value;
              // 為了讓父元件可以修改值,發出一個事件
              this.$emit('num1change', this.dnumber1);
            }
          }
        }
      }
    })
  </script>
</body>
</html>