美文网首页Vue.js开发技巧Vue.js 资料
不同场景下组件的数据通信

不同场景下组件的数据通信

作者: VinegarWJ | 来源:发表于2018-03-27 16:21 被阅读41次

    父子组件的数据通信


    1.父组件传递数据给子组件(props)

    2.子组件传递数据给父组件 (回调函数)

    <div id  ="parent">

    <h3>{{parentName}}</h3>

    <child :change-parent-name =changeParentName"></child>

    </div>

    data--->parentName ='smallDog'

    methods:{

    changeParentName(newName){

    this.parentName = newName

    }

    }

    ----------------------------------------------

    <div id ="child">

    <button @click ="() =>changeParentName(newName)">click me!</button>

    </div>

    data--->newName ="BigDog"

    props:{

    changeParentName:{type:Function, default:()=>{}}

    }

    兄弟组件的数据通信


    <div id="child1">

    <h1>{{firstChildName}}</h1>

    </div>

    props:{firstChildName:{type:String, default:''}}

    --------------------

    <div id="child2">

    <button @click=""changeFirstChildName"></buttom>

    </div>

    props:{changeFirstChildName:{type:Function,default:()=>{}}}

    ---------------------

    <div id="parent">

    <h1>{{parent}}</h1>

    <child1 :first-child-name="firstChildName"></child1>

    <child2 :change-first-child-name="changeFirstChildName"></child2>

    </div>

    data---->parent:mother

    ----->firstChildName:xiaoming

    methods:{

    changeFirstChildName(){

    this.firstChildName = 'xiaohong'

    }

    }

    child1,child2 分别是两个子组件,parent是父组件

    如果是孩子组件里面的话 就只要定义props就够,而这些props 根据在父组件里面绑定的名字是一样的

    而是在父亲组件里面的话,需要定义data基本的数据和更改数据的方法即可

    相关文章

      网友评论

        本文标题:不同场景下组件的数据通信

        本文链接:https://www.haomeiwen.com/subject/rglscftx.html