search

Home  >  Q&A  >  body text

About "props should not be changed inside child components" - Stack Overflow

Official documentation says that props should not be changed inside child components

Vue.component('todo-list',{
    props:['msg'],
    template:'<li>{{msg.text}}<button @click="fun">click</button></li>',
    methods:{
        fun:function(){
            alert(this.msg.text='芒果');
        }
    }
});
        
new Vue({
    el:'#app',
    data:{
        grocery:[
            {text:'苹果'},
            {text:'香蕉'},
            {text:'菠萝'}
        ]
    }
});
<p id="app">
    <ol>
        <todo-list v-for="(item,index) in grocery" key="index" :msg="item"></todo-list>
    </ol>
</p>

I don’t know if I change the prop inside the subcomponent like this? Anyway, no error was reported.
What do you mean by changing prop inside a subcomponent?


Some people say that the value of the parent component is not changed

Vue.component('todo-list',{
    props:['msg'],
    template:'<li @click="funn">{{msg.text}}<button @click.stop="fun">click</button></li>',
    methods:{
        fun:function(){
            alert(this.msg.text='芒果');
        },
        funn:function(n){
            alert(this.msg.text);
        }
    }
});

I am getting more and more confused. Hasn’t it changed? Please explain the specific points

仅有的幸福仅有的幸福2808 days ago794

reply all(4)I'll reply

  • 高洛峰

    高洛峰2017-06-12 09:31:56

    It can be regarded as modifying the data of the parent component, and can be used in some situations where you don’t want to write $emit

    The official does not strictly oppose this method

    reply
    0
  • 迷茫

    迷茫2017-06-12 09:31:56

    The items in the parent component will not change. . . What's the point of changing msg?
    If it can be called again. . . The next time msg is called it will still be equal to item

    reply
    0
  • 迷茫

    迷茫2017-06-12 09:31:56

    reply
    0
  • 某草草

    某草草2017-06-12 09:31:56

    It’s just an appearance, the original item value passed in has not changed. In vue1.0, you can use dispatch to pass values ​​to change the value and status of the item

    reply
    0
  • Cancelreply