一 .prop和$emit
prop父子组件通信类型:直接在标签里面给子组件绑定属性和方法,对于属性我们可以直接通过子组件声明的prop拿到,对于父元素的方法,我们可以通过 this.$emit触发。
父组件:
<template>
<div class="father" >
<input v-model="mes" /> <button @click="send" >对子组件说</button>
<div>子组件对我说:{
{ sonMes }}</div>
<son :fatherMes="sendSonMes" @sonSay="sonSay" />
</div>
</template>
<script>
import son from './son'
export default {
name:'father',
components:{
son /* 子组件 */
},
data(){
return {
mes:'',
sendSonMes:'', /* 来自子组件的信息 */
sonMes:'' /* 发送给子组件的信息 */
}
},
methods:{
/* 传递给子组件 */
send(){
this.sendSonMes = this.mes
},
/* 接受子组件信息 */
sonSay(value){
this.sonMes = value
},
},
}
</script>
我们这里只需要将给子组件的数据fatherMes和提供给子组件的方法 sonSay 通过标签方式传递给子组件。
子组件:
<template>
<div class="son" >
<div> 父组件对我说:{
{ fatherMes }} </div>
<input v-model="mes" /> <button @click="send" >对父组件说</button>
</div>
</template>
<script>
export default {
name:'son',
props:{
fatherMes:{
type:String,
default:''
}
},
data(){
return {
mes:''
}
},
methods:{
send(){
this.$emit('sonSay',this.mes)
}
},
}
</script>>
子组件通过props来定义接受父组件传递过来的信息,我们就可以直接通过this获取到,对于父组件传递的事件,我们可以通过this.$emit来触发事件。
缺点:
1.子组件虽然不能直接对父组件prop进行重新赋值,但是当父组件是引用类型的时候,子组件可以修改父组件的props下面的属性。
2.跨层级通信,兄弟组件通讯困难
二.this. c h i l d r e n 与 t h i s . children与 this. children与this.parent 或 ref
无需再给子组件绑定事件和属性,只需要在父组件和子组件声明发送和接受数据的方法。
<template>
<div class="father" >
<input v-model="mes" /> <button @click="send" >对子组件说</button>
<son2 v-if="false" /> //注意这里son2是fasle所以const currentChildren = this.$children[0]可以访问到son,当son2可以控制为true时,这里将会报错。
<div>子组件对我说:{
{ sonMes }}</div>
<son />
</div>
</template>
<script>
import son from './son'
import son2 from './son2'
export default {
name:'father',
components:{
son ,/* 子组件 */
son2
},
data(){
return {
mes:'',
sendSonMes:'', /* 来自子组件的信息 */
sonMes:'' /* 发送给子组件的信息 */
}
},
methods:{
/* 传递给子组件 */
send(){
/* 因为son组件是第一个有效组件所以直接去下标为0的组件 */
const currentChildren = this.$children[0]
currentChildren.accept(this.mes)
},
/* 接收子组件的信息 */
accept(value){
this.sonMes = value
}
},
}
</script>
<template>
<div class="son" >
<div> 父组件对我说:{
{ fatherMes }} </div>
<input v-model="mes" /> <button @click="send" >对父组件说</button>
</div>
</template>
<script>
export default {
name:'son',
data(){
return {
mes:'',
fatherMes:''
}
},
methods:{
/* 接受父组件内容 */
accept(value){
this.fatherMes = value
},
/* 向父组件发送信息 */
send(){
this.$parent.accept(this.mes)
},
},
}
</script>
//注意这里son2是fasle所以const currentChildren = this. c h i l d r e n [ 0 ] 可 以 访 问 到 s o n , 当 s o n 2 可 以 控 制 为 t r u e 时 , 这 里 将 会 报 错 : c o n s t c u r r e n t C h i l d r e n = t h i s . children[0]可以访问到son,当son2可以控制为true时,这里将会报错:const currentChildren = this. children[0]可以访问到son,当son2可以控制为true时