Vue父子組件之間的通信

如果你之前有了解過的話,那麼只需要看前面這一部分!

終極思想

  • 父向子傳值 把握中間值props

    • 子組件在props中創建一個屬性,用以接收父組件傳過來的值
    • 父組件中註冊子組件
    • 在子組件標籤中添加子組件props中創建的屬性
    • 把需要傳給子組件的值賦給該屬性
  • 子向父傳值 把握自定義函數的使用

    • 子組件中需要以某種方式例如點擊事件的方法來觸發一個自定義事件
    • 將需要傳的值作爲$emit的第二個參數,該值將作爲實參傳給響應自定義事件的方法
    • 在父組件中註冊子組件並在子組件標籤上綁定對自定義事件的監聽

正文開始

父組件向子組件傳遞信息

<div id="app">
        <Counter :count="num"></Counter>
        <Counter :count="num"></Counter>
    </div>
    <template id="counter">
        <div>
            <button @click="n++">+</button>
            {{n}}
        </div>
    </template>
    <script>
        Vue.component('Counter', {
            props: ['count'],
            template: "#counter",
            data: function () {
                return {
                    n: this.count
                }
            }
        })
        new Vue({
            el: "#app",
            data: {
                num: 10
            }
        })
    </script>

結果輸出:
在這裏插入圖片描述

子向父組件傳值

<!-- Prop 作爲初始值傳入後,子組件想把它當作局部數據來用; -->
    <div id="app">
        <p>父級total:{{total}}</p>
        <button @click="incrementTotal">父級點擊</button>
        <hr>
        <Counter v-on:increment="incrementTotal">

        </Counter>
    </div>

    <template id="counter">
        <div style="border:1px solid blue">
            <button @click="increment">子級加
                {{counter}}
            </button>
        </div>
    </template>
    <script>
        Vue.component('Counter', {
            template: "#counter",
            data:function(){
                return {counter:0}
            },
            methods:{
                increment:function(){
                    this.counter += 1;
                    this.$emit("increment")
                }
            }
        })
        var vm = new Vue({
            el: "#app",
            data: {
                total:0
            },
            methods:{
                incrementTotal:function(){
                    this.total += 2
                }
            }
        })
    </script>

輸出結果:
在這裏插入圖片描述

綜合應用

<div id="app">
    <com1 v-bind:parentmsg="msg" @func="getMsgFormSon"></com1>
  </div>
  
  <template id="tmpl">
    <div>
      <h1>這是子元素 --- {{ parentmsg }}</h1>
      <input type="button" value="向父組件傳遞消息" @click="sendMsg">
    </div>
  </template>

  <script>

    var com1 = {
      template: '#tmpl',
      data() {
        return {
          msg: '做一個孝順的孩子,給爸爸一些錢去揮霍吧!'
        }
      },
      props: ['parentmsg'],
      methods: {
        sendMsg() {
          this.$emit('func', this.msg)
        }
      }
    }

    // 創建 Vue 實例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        msg: '這是父組件中的數據,爸爸有100塊錢,my son, 你要不',
        msgFormSon: ''
      },
      methods: {
        getMsgFormSon(data) {
          this.msgFormSon = data
          console.log(this.msgFormSon)
        }
      },
      components: {
        com1
      }
    });
  </script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章