vue填坑-父子組件互相傳值的問題

1. 父子傳值 props

所有的 props 都是單向往下的,父組件 property 更新會影響子組件的,反過來則不會;另外,每次父組件中對應屬性發(fā)生改變,子組件中的所有 props 都會被更新為最新的值。所以在子組件中,不應該對 props 進行更改

<div id="app">
    <p>{{ message }}</p>
    <input type="text" v-model="message">
    <child :msg="message"></child>
</div>
<template id="child">
    <p>從父組件傳來的msg: {{ msg }}</p>
</template>
<script>
    Vue.component('child', {
        template: '#child',
        props: ['msg']
    })
    new Vue({
        el: '#app',
        data: {
            message: 'hello props'
        }
    })
</script>

在線demo

2. 子組件向父組件傳遞數(shù)據(jù) 自定義事件

使用 v-on
所有Vue實例都實現(xiàn)了Events接口,即: 通過 $on(eventName) 監(jiān)聽事件 ; 通過 $emit(eventName) 觸發(fā)事件

<div id="count">
    <p>{{ total }}</p>
    <count-btn v-on:add="incrementTotal"></count-btn>
    <count-btn v-on:add="incrementTotal"></count-btn>       
</div>
<template id="child">
    <div>
        <button @click="add">{{ count }}</button>
    </div>
</template>
<script>
    Vue.component('count-btn', {
        template: '#child',
        data () {
            return {
                count: 0
            }
        },
        methods: {
            add () {
                this.count++
                this.$emit('add')
            }
        }
    })
    new Vue({
        el: '#count',
        data: {
            total: 0
        },
        methods: {
            incrementTotal () {
                this.total++
            }
        }
    })
</script>

在線demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容