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

父子组件的数据通信



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基本的数据和更改数据的方法即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。