【vue】父向子組件傳參、子組件向父傳參


1.父向子組件傳參

App.vue為父,引入componetA組件之后,則可以在App.vue中使用標簽(注意駝峰寫法要改成componet-a寫法,因為html對大小寫不敏感,componenta與componentA對於它來說是一樣的,不好區分,所以使用小寫-小寫這種寫法)。

而子組件componetA中,聲明props參數’msgfromfa’之后,就可以收到父向子組件傳的參數了。例子中將msgfromfa顯示在<p>標簽中。

App.vue中

<component-a msgfromfa="( 不積跬步,無以至千里;不積小流,無以成江海)"></component-a>
import componentA from './components/componentA'
export default {
    new Vue({
        components: {
          componentA
        }
    })
}

componentA.vue中

<p>{{ msgfromfa }}</p>
export default {
    props: ['msgfromfa']
}

2.子組件向父傳參

2.1  .$emit

用法:vm.$emit( event, […args] ),觸發當前實例上的事件。附加參數都會傳給監聽器回調。
例子:

App.vue中component-a綁定了自定義事件”child-say”。

子組件componentA中,單擊按鈕后觸發”child-say”事件,並傳參msg給父組件。父組件中listenToMyBoy方法把msg賦值給childWords,顯示在<p>標簽中。
App.vue中

<p>Do you like me? {{childWords}}</p>
<component-a msgfromfa="(Just Say U Love Me)" v-on:child-say="listenToMyBoy"></component-a>
import componentA from './components/componentA'
export default {
    new Vue({
        data: function () {
            return {
              childWords: ""
            }
        },
        components: {
          componentA
        },
        methods: {
            listenToMyBoy: function (msg){
              this.childWords = msg
            }
        }
    })
}

componentA.vue中

<button v-on:click="onClickMe">like!</button>
import componentA from './components/componentA'
export default {
    data: function () {
        return {
          msg: 'I like you!'
        }
    },
    methods: {
      onClickMe: function(){
        this.$emit('child-say',this.msg);
      }
    }
}

2.2  .$dispatch

用法:vm.$dispatch( event, […args] ),派發事件,首先在實例上觸發它,然后沿着父鏈向上冒泡在觸發一個監聽器后停止。
例子:App.vue中events中注冊”child-say”事件。子組件componentA中,單擊按鈕后觸發”child-say”事件,並傳參msg給父組件。父組件中”child-say”方法把msg賦值給childWords,顯示在<p>標簽中。

App.vue中

<p>Do you like me? {{childWords}}</p>
<component-a msgfromfa="(Just Say U Love Me)"></component-a>
import componentA from './components/componentA'
export default {
    new Vue({
        events: {
            'child-say' : function(msg){
              this.childWords = msg
            }
        }
    })
}

componentA.vue中

    
<button v-on:click="onClickMe">like!</button>
import componentA from './components/componentA'
export default {
    data: function () {
        return {
          msg: 'I like you!'
        }
    },
    methods: {
      onClickMe: function(){
        this.$dispatch('child-say',this.msg);
      }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM