undefinedfix
Sign in

Why can't I listen to the change of the value passed by the parent component

eqtmd edited in Fri, 23 Sep 2022

My subcomponent created has got the passed value, but my data change subcomponent watch can't monitor it. Please see what's wrong with me. Thank you

Parent component

<template>
    <div>
        <div class="bar-1">
                <el-radio-group v-model="radio">
                    <el-radio-button label="DAY">日</el-radio-button>
                    <el-radio-button label="MONTH">月</el-radio-button>
                    <el-radio-button label="YEAR">年</el-radio-button>
                </el-radio-group>
            
                <barchart :childmsg="radio"></barchart>
        </div>

    </div>
</template>
 
<script>

export default {
    data() {
        return {
            radio: 'DAY',
        };
    }
};
</script>




Subcomponents

export default {
    props: ["childmsg"],
    watch: {
        childmsg: {
                handler(newValue, oldValue) {
                    console.log(newValue);
                }
            }
    },
    created() {
        console.log(this.childmsg);//这里已经获取了父组件传过来的值
    },
}
4 Replies
dnqlo
commented on Fri, 23 Sep 2022

Your parent component is bound to radio1

Amer
commented on Sat, 24 Sep 2022

Add immediate : Let's try. My test is feasible

export default {
    props: ["childmsg"],
    watch: {
        childmsg: {
                handler(newValue, oldValue) {
                    console.log(newValue);
                },
                immediate: true
            }
    },
    created() {
        console.log(this.childmsg);//这里已经获取了父组件传过来的值
    },
}
bastian
commented on Sat, 24 Sep 2022

Has the child component been registered in the parent component? I ran your code for a while, and I can monitor the changes of radio

components: {
    barchart
},
ktwyj
commented on Sat, 24 Sep 2022

The problem lies in the radio of the parent component, < El radio button: label = day > < El radio button > < El radio button: label = month > < El radio button: label = year > < El radio button > if it is a variable, remember to add a colon before the label: