鍍金池/ 問答/Java  PHP  Python  網(wǎng)絡安全  HTML/ vue父子通信時,當父傳子,子再傳父,最后父傳子,如何實現(xiàn)更新,如下圖和代碼

vue父子通信時,當父傳子,子再傳父,最后父傳子,如何實現(xiàn)更新,如下圖和代碼

問題

我想在父組的輸入框(紅色)里,輸入,然后子組件實現(xiàn)更新

clipboard.png

父組件

<template>
    <div>
        <test8Title :h1="h1" :arr="arr" v-on:childerToFather="fatherFn($event)"></test8Title>
        <div>我是父組件: <input type="text" v-model="h1"> </div>
    </div>
</template>

<script>
import test8Title from '@/components/test8Title'
export default {
    components:{
        test8Title
    },
    data() {
        return {
            h1:"",
            arr:[
                {id:1,name:"jie1"},
                {id:2,name:"jie2"},
                {id:3,name:"jie3"},
            ]
        };
    },
    methods:{
        fatherFn(msg){
            this.h1 = msg;
        }
    }
};
</script>

子組件

<template>
    <div>
        <ul>
            <li v-for="item in arr" :key="item.id">
                {{item.id}}--{{item.name}}
            </li>
        </ul>
        <div>
            子組件輸入:
            <input type="text" v-model="h1Text">
            <button @click="childerFn">子改父</button>
        </div>
        
    </div>
</template>

<script>
export default {
    props: {
        h1: {
            type: String,
            required: true
        },
        arr: {
            type: Array,
            required: true
        }
    },
    data() {
        return {
            h1Text:''
        };
    },
    methods:{
        childerFn(){
            this.$emit('childerToFather',this.h1Text)
        }
    }
};
</script>



回答
編輯回答
情未了

你子組件的輸入框是綁定h1Text的,但是你沒有把h1和h1Text建立聯(lián)系
你可以在子組件里給h1加個watch

watch: {
    'h1': {
        handler(val){
            this.h1Text = val
        },
        immediate: true
    }
}
2017年5月24日 20:47