vue父子组件通信

1.父向子组件通信通过props传值

//父组件
<template>
    <header-box :header-title="title"></header-box>
</template>
<script>
    import header from './header';
    export default{
        name:'index',
        data(){
            return{
                title:'首页'
            }
        },
        components:{
           'header-box':header,
       }
    }
</script>
//子组件
<template>
    <div>{{textTitle}}</div>
</template>
<script>
    export default{
        name:"header",
        props:['header-title'],
        data(){
            return{
                textTitle:this.header-title
            }
        },
    }
</script>

2.子组件向父组件通信子组件定义一个事件用$emit传值

//子组件
<template>
    <button @click="incrementCounter">{{num}}</button>
</templete>
<script>
export default{
    name:'button',
    data(){
        return{
            num:0,
        }
    },
    metheds:{
        incrementCounter:function(){
            this.$emit("change-value",this.num++)
        }
    }
}
</script>
//父组件
<template>
    <button-center @change-value="num"></button-center>
</template>
<script>
import button from "./button"
export default{
    name:'parent',
    data(){
        return{
            counter:0,
        }
    },
    components:{
        "buttonCenter":button
    },
    metheds:{
        num:function(){
            this.counter++
        }
    }
}
<script>
    原文作者:沈小白
    原文地址: https://segmentfault.com/a/1190000017883395
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞