vue中子组件改变父组件数据的两种方法

方法一:这个方法不用在父组件那里写自定义事件,对于处理一些小数据简单易用

<body>
    <div id="app">
        <child :mag.sync='msg'></child>
        msg:{{msg}}
    </div>
</body>
<script>  
    Vue.component('child',{
        template:`
            <div>
                <button @click="open">点击我</button>
            </div>
        `,
        prop:['msg'],
        data:function(){
            return{
                mag:this.msg
            }
        },
        methods:{
            open(){
                console.log(this.mag);
                this.$emit('update:mag',true);
            }
        }
    })
 new Vue({
        el:'#app',
        data:{
            msg:'hello world',
        },
        methods:{
            toshow(msg){
                this.msg=msg;
            }
        }
    })
</script>

方法二:通过自定义事件

<body>
    <div id="app">
        <child2 :msg='msg' @showbox="toshow"></child2>
        msg:{{msg}}
    </div>
</body>
<script>  
    Vue.component('child2',{
        template:`
            <div>
                <button @click="open">点击我2</button>
            </div>
        `,
        prop:['msg'],
        data:function(){
            return{
                msg:this.msg
            }
        },
        methods:{
            open(){
                console.log(this.msg);
                this.$emit('showbox',true);
            }
        }
    })
    new Vue({
        el:'#app',
        data:{
            msg:'hello world',
        },
        methods:{
            toshow(msg){
                this.msg=msg;
            }
        }
    })
</script>

猜你喜欢

转载自blog.csdn.net/weixin_38098192/article/details/81113804