Search code examples
vue.jsvue-componentvuexvue-reactivityvue-props

Vue stored valued through props not being reactive


So I pass value using [props] and stored it in child component's data. However, when passing [props] value changes from parent, it's not updating in child component's data. Is there a fix for this..?

Here is the link to w3 test (I tried to clarify the problem as much as possible here)

<div id='app'>
    <div id='parent'>
        <button @click='current_value()'>Click to see parent value</button>
        <br><br>
        <button @click='change_value($event)'>{{ txt }}</button>
        <br><br>
        <child-comp :test-prop='passing_data'></child-comp>
    </div>
    <br><br>
    <center><code>As you can see, this methods is <b>NOT</b> reactive!</code></center>
</div>
<script>

new Vue({
    el: "#parent",
    data: {
        passing_data: 'Value',
        txt: 'Click to change value'
    },
    methods: {
        current_value(){
            alert(this.passing_data);   
        },
        change_value(e){
            this.passing_data = 'New Vaule!!';
            this.txt = 'Now click above button again to see new value';
            e.target.style.backgroundColor = 'red';
            e.target.style.color = 'white';
        }
    },
    components: {
        "child-comp": {
            template: `
                <button @click='test()'>Click here to see child (stored) value</button>
            `,
            props: ['test-prop'],
            data(){
                return {
                    stored_data: this.testProp
                }
            },
            methods: {
                test(){
                    alert(this.stored_data);
                }
            },
            watch: {
                stored_data(){
                    this.stored_data = this.testProp;
                }
            }
        }
    }
});

Solution

  • Props have one way data flow, that's why it doesn't react when you update it from the parent component. Define a clone of your prop at data to make it reactive, and then you can change the value within the child component.