Vue 通过 props 存储价值而不是被动的

Vue stored valued through props not being reactive

所以我使用 [props] 传递值并将其存储在子组件的数据中。但是,当从父级传递 [props] 值更改时,它不会更新子组件的数据。这个问题有解决办法吗?

Here is the link to w3 test(这里我尽量把问题说清楚了)

<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;
                }
            }
        }
    }
});

Props have one way data flow, that's why it doesn't react when you update it from the parent component. 在数据处定义一个 prop 的克隆以使其响应,然后您可以更改子组件中的值。

简短回答:您不需要 stored_data。直接用alert(this.testProp)

长答案:创建子组件时,stored_datathis.testProp 获取它的值。但是 data 是本地的,不会自动改变。这就是为什么你需要观看 testProp 并重新设置它。但是由于一个简单的错误而无法正常工作,您的 watch 应该是:

            watch: {
                testProp(){ // here was the mistake
                    this.stored_data = this.testProp;
                }
            }