在说如何实现通信之前,我们先来建两个组件.vue和child.vue作为示例的基础。
//父组件
<div>
<h1>我是父组件!</h1>
<child></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
}
</script>
//子组件
<h3>我是子组件!</h3>
</template>
<script>
</script>
这两部分的代码都很清晰明了,父组件通过的方式导入子组件,并在属性中注册,然后子组件就可以用标签的形式嵌进父组件了。运行.vue后的效果是这样的:
示例效果一
1.通过prop实现通信
子组件的props选项能够接收来自父组件数据。没错,仅仅只能接收,props是单向绑定的,即只能父组件向子组件传递,不能反向。而传递的方式也分为两种:
(1)静态传递
子组件通过props选项来声明一个自定义的属性,然后父组件就可以在嵌套标签的时候,通过这个属性往子组件传递数据了。
<template>
<div>
<h1>我是父组件!</h1>
<child message="我是子组件一!"></child> //通过自定义属性传递数据
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
}
</script>
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
props: ['message'] //声明一个自定义的属性
}
</script>
(2)动态传递
我们已经知道了可以像上面那样给 props 传入一个静态的值,但是我们更多的情况需要动态的数据。这时候就可以用 v-bind 来实现。通过v-bind绑定props的自定义的属性,传递去过的就不是静态的字符串了,它可以是一个表达式、布尔值、对象等等任何类型的值。
<template>
<div>
<h1>我是父组件!</h1>
<child message="我是子组件一!"></child>
<child v-bind:message="a+b"></child>
<child v-bind:message="msg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
data() {
return {
a:'我是子组件二!',
b:112233,
msg: '我是子组件三!'+ Math.random()
}
}
}
</script>
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
props: ['message']
}
</script>
出来的效果是这样的:
示例效果二
2.通过$ref 实现通信
对于ref官方的解释是:ref 是被用来给元素或子组件注册引用信息的。引用信息将会注册在父组件的 $refs 对象上。 看不懂对吧?很正常,我也看不懂。那应该怎么理解?看看我的解释:
那如何通过$ref 实现通信?下面我将上面prop实现的功能,用$ref实现一遍:
<template>
<div>
<h1>我是父组件!</h1>
<child ref="msg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
mounted: function () {
console.log( this.$refs.msg);
this.$refs.msg.getMessage('我是子组件一!')
}
}
</script>
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
data(){
return{
message:''
}
},
methods:{
getMessage(m){
this.message=m;
}
}
}
</script>
从上面的代码我们可以发现,通过ref=‘msg’可以将子组件child的实例指给$ref,并且通过.msg.()调用到子组件的方法,将参数传递给子组件。下面是“ .log( this.$refs.msg);”打印出来的内容,这可以让大家更加了解,究竟通过ref我们获取了什么:
.log
最后的效果是这样的:
示例效果三
这里再补充一点就是,prop和$ref之间的区别:3.通过$emit 实现通信
上面两种示例主要都是父组件向子组件通信,而通过$emit 实现子组件向父组件通信。 对于$emit官网上也是解释得很朦胧,我按我自己的理解是这样的: vm.$emit( event, arg ) $emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
<template>
<div>
<h1>{{title}}</h1>
<child @getMessage="showMsg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
data(){
return{
title:''
}
},
methods:{
showMsg(title){
this.title=title;
}
}
}
</script>
<template>
<h3>我是子组件!</h3>
</template>
<script>
export default {
mounted: function () {
this.$emit('getMessage', '我是父组件!')
}
}
</script>
———END———
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,永久会员只需109元,全站资源免费下载 点击查看详情
站 长 微 信: nanadh666