vue组件间通信(props、$ref、$emit)函数讲解

3,679 阅读1分钟

这是我参与8月更文挑战的第12天,活动详情查看:8月更文挑战

组件是 vue.js 最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互引用。那么组件间如何通信,也就成为了vue中重点知识了。这篇文章将会通过props、refref和 emit 这几个知识点,来讲解如何实现父子组件间通信。

父组件:

<template>  
    <div>父组件的toCity{{toCity}}</div>  
    <train-city @showCityName="updateCity" :sendData="toCity"></train-city>  
<template>  
<script>  
  import TrainCity from "./train-city";  
  export default {  
    name:'index',  
    components: {TrainCity},  
    data () {  
      return {  
        toCity:"北京"  
      }  
    },  
    methods:{  
      updateCity(data){//触发子组件城市选择-选择城市的事件  
        this.toCity = data.cityname;//改变了父组件的值  
        console.log('toCity:'+this.toCity)  
      }  
    }  
  }  
</script>

子组件:

<template>  
  <div class="train-city">  
    <h3>父组件传给子组件的toCity:{{sendData}}</h3>   
    <br/><button @click='select(`大连`)'>点击此处将‘大连’发射给父组件</button>  
  </div>  
</template>  
<script>  
  export default {  
    name:'trainCity',  
    props:['sendData'], // 用来接收父组件传给子组件的数据  
    methods:{  
      select(val) {  
        let data = {  
          cityname: val  
        };  
        this.$emit('showCityName',data);//select事件触发后,自动触发showCityName事件  
      }  
    }  
  }  
</script>

这两部分的代码都很清晰明了,父组件通过import的方式导入子组件,并在components属性中注册,然后子组件就可以用标签<train-city>的形式嵌进父组件了。

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>

 <!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
 <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 对象上。

看不懂对吧?很正常,我也看不懂。那应该怎么理解?看看我的解释:

  1. 如果ref用在子组件上,指向的是组件实例,可以理解为对子组件的索引,通过$ref可能获取到在子组件里定义的属性和方法。

  2. 如果ref在普通的 DOM 元素上使用,引用指向的就是 DOM 元素,通过$ref可能获取到该DOM 的属性集合,轻松访问到DOM元素,作用与JQ选择器类似。

<!-- 父组件 -->
<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.getMessage()调用到子组件的getMessage方法,将参数传递给子组件。这里再补充一点就是,propref,并且通过.msg.getMessage()调用到子组件的getMessage方法,将参数传递给子组件。 这里再补充一点就是,prop和ref之间的区别:

  1. prop 着重于数据的传递,它并不能调用子组件里的属性和方法。像创建文章组件时,自定义标题和内容这样的使用场景,最适合使用prop。
  2. $ref 着重于索引,主要用来调用子组件里的属性和方法,其实并不擅长数据传递。而且ref用在dom元素的时候,能使到选择器的作用,这个功能比作为索引更常有用到。

3.通过$emit 实现通信

上面两种示例主要都是父组件向子组件通信,而通过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>