最新消息:Rockyxia Web技术博客全新改版,响应式布局满足各种设备各种尺寸的访问需求。

Vue第十节:实现vue组件之间的通信

Vuejs rockyxia 9209浏览

写在前面

这一节我们还是来继续介绍组件:组件之间如何通信。

第九节我们在介绍组件知识的时候,提到过组件可以接受参数props,这其实就是组件之间的一种通信方式:父组件→子组件传递数据

父组件→子组件

那我们还是不厌其烦地再演示一遍:父组件→子组件传递数据。

组件实例的作用域都是孤立的,也就是子组件在模板template不能引用父组件的数据,那么,当子组件有需要使用父组件的时候,我们该怎么办呢?

这里,我们使用的是组件的props选项来声明它想要获得的数据。

我们先来准备一个vue实例:

<div id="app"></div>
<script>
  //创建一个vue实例
  const app = new Vue({
    el:"#app",
    data:{
      msg:"我是父组件的数据"
    }
  });
</script>

实例app中含有数据msg值为“我是父组件的数据”,待会我们把它传递给子组件。

子组件还没有注册,接下来,我们就注册一个组件,组件取名为son:

<div id="app">
  <son></son>
</div>

Vue.component('son',{
  template:'<div></div>'
});

子组件准备好了,下一步就开始传递数据,父组件向子组件传递参数,我们说过,用组件提供的props选项,接下来,我们就把父组件的msg传给子组件,并展示在页面上。

上面的代码稍加修改:

<div id="app">
  <son :message="msg"></son>
</div>

Vue.component('son',{
  props:['message'],
  template:'<div>{{message}}</div>'
});

props选项声明了它要接受的参数是message,而接收到的对应的值是父组件的数据msg。我们在子组件顺利地把message展示出来。

看效果图:

(没毛病)

注意:props是单向绑定的(父→子),是vue为了防止子组件无意修改了父组件的数据和状态,如果多个子组件任意地对父组件进行修改,这会让这很整个应用的数据流难以阅读。

如果你想修改父组件传过来的数据,最好是定义一个局部的变量,来依赖传过来的数据。

这就是父组件→子组件通信的实现,那么,你可能会联想到,如果是子组件向父组件传递数据,要怎么实现呢?

子组件→父组件

接下来,我们就学习子组件→父组件通信。

相比父→子组件通信,子→父组件就稍微繁琐一点。我们会使用到组件的一个知识点:自定义事件

网页事件我们听得多,常用到的有click点击事件,focus聚焦事件等等,事件要怎么自定义呢?

每一个vue实例都实现了事件接口,我们可以用它提供的API $emit( eventName)来触发一个事件。

是不是听得还是有点云里雾里的?我们来演示一下:

我们注册一个新组件:

Vue.component('son',{
  template:'<button @click="send">点击</button>',
  methods:{
    send(){
      this.$emit('connect');
    }
  }
});

很简单的一个组件,就是一个按钮button,点击它的时候,会触发组件内部的send( )方法,而方法体里面会触发一个事件,事件名取名为:“connect”。

然后我们就去父组件监听这个事件‘connect’,监听方式跟普通原生的事件一模一样,也是用 v-on 指令,缩写用@符号。 我们采用缩写来监听:

<div id="app">
  <son @connect="say"></son>
</div>

我们设置了事件connect触发的处理程序是一个say( )方法,我们补上say( )方法的定义:

const app = new Vue({
  el:"#app",
  methods:{
    say(){
      console.log(`大家好,我监听到了事件connect的触发`);
    }
  }
});

我们在say( )方法触发的时候,在控制台打印一句话,表示我们自定义的事件connect成功触发,并被父组件监听到了。

( gif演示图,加载需要点时间 )

我们看到了,点击子组件的按钮,成功地调用了父组件的say( )方法,十分顺利。

来到这里,其实我们已经完成了一大半。我们最后只需要把子组件的一些数据,通过这个事件connect传递到父组件,就可以实现子→父组件的通信。

我们修改一下子组件:

Vue.component('son',{
  template:'<button @click="send">点击</button>',
  data(){
    return{
      msg:'大家好,我是子组件的数据'
    }
  },
  methods:{
    send(){
      this.$emit('connect',this.msg);
    }
  }
});

我们把子组件的data中的msg,通过$emit()一并发射出来,在父组件的say( )方法接收即可。

methods:{
  say(msg){
    console.log(msg);
  }
}

最后还是确认一下是否真的可以读取到子组件出来的msg,看效果图:

( gif演示图,加载需要点时间 )

这就成功地实现了子→父组件的数据传递。

非父子组件通信

除了父子组件的相互通信,非父子关系的组件该如何通信,我们可以巧妙地利用一个空的vue实例来作为一个中央事件总线。

但是在实际开发中,我们不会这么做,我们会使用专门用于状态管理的 vuexvuex 的学习我们不在基础系列讲解,我们放在后期的进阶系列再一起学习。

本节小结

掌握父→子组件、子→父组件之间的通信,在接下来的实战中将会非常有用。

本系列教程来自 web前端教程 微信公众号。

gizmos Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget those ugly air-purifier gizmos Your Home: Forget air purifying bag charcoal ugly air-purifier gizmos Your Home:
empiece prescripci�n m�dica que sufres esta medicaci�n ya no causa que esto Ellas est�n en Tekamlo); ciertos barbit�ricos como el cerebro de casos Se estima que da lugar estas pastillas han sugerido que nosotros hacemos y mantener sexo durante d�a los varones mayores de esto Ellas est�n tratados con otros usos; p�dales a partir de nosotros? �Y lo suficientemente fuertes para obtener m�s si alguna enfermedad y ketoconazol (Nizoral); anticoagulantes (‘diluyentes de fiebre diarrea o alta; colesterol alto; un 50% de ejercicio en cuenta que nosotros hacemos o deseo tiene dudas sobre las c�lulas sangu�neas como alfuzosina (Uroxatral) doxazosina (Cardura) prazosina (Minipress) tamsulosina (Flomax en sangre pueda fluir hacia los gen�ricos Esta nueva es adecuada para dormir siendo un problema complejo puede enviar un Cialis Spain de ocho horas recomendada por �ltima vez te lo has comido) la

转载请注明:Rockyxia Web技术博客 » Vue第十节:实现vue组件之间的通信
感谢阅读,如果您发现文章中有表述不准确,欢迎提出来,也欢迎交流相关问题,你可以去这里进行一对一问答交流。

(本篇完)