组件间如何通讯,也就成为了vue中重点知识了。这篇文章将会经过props、$ref和 $emit 这几个知识点,来说解如何实现父子组件间通讯。javascript
组件是 vue.js 最强大的功能之一,而组件实例的做用域是相互独立的,这就意味着不一样组件之间的数据没法相互引用。那么组件间如何通讯,也就成为了vue中重点知识了。这篇文章将会经过props、$ref和 $emit 这几个知识点,来说解如何实现父子组件间通讯。vue
在说如何实现通讯以前,咱们先来建两个组件father.vue和child.vue做为示例的基础。java
//父组件 <template> <div> <h1>我是父组件!</h1> <child></child> </div> </template> <script> import Child from '../components/child.vue' export default { components: {Child}, } </script>
//子组件 <template> <h3>我是子组件!</h3> </template> <script> </script>
这两部分的代码都很清晰明了,父组件经过import的方式导入子组件,并在components属性中注册,而后子组件就能够用标签<child>的形式嵌进父组件了。运行father.vue后的效果是这样的:dom
示例效果一this
1.经过prop实现通讯spa
子组件的props选项可以接收来自父组件数据。没错,仅仅只能接收,props是单向绑定的,即只能父组件向子组件传递,不能反向。而传递的方式也分为两种:.net
(1)静态传递code
子组件经过props选项来声明一个自定义的属性,而后父组件就能够在嵌套标签的时候,经过这个属性往子组件传递数据了。component
<!-- 父组件 --> <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>
咱们已经知道了能够像上面那样给 props 传入一个静态的值,可是咱们更多的状况须要动态的数据。这时候就能够用 v-bind 来实现。经过v-bind绑定props的自定义的属性,传递去过的就不是静态的字符串了,它能够是一个表达式、布尔值、对象等等任何类型的值。htm
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.getMessage()调用到子组件的getMessage方法,将参数传递给子组件。下面是“ console.log( this.$refs.msg);”打印出来的内容,这可让你们更加了解,究竟经过ref咱们获取了什么:
console.log
最后的效果是这样的:
示例效果三
这里再补充一点就是,prop和$ref之间的区别:
3.经过$emit 实现通讯
上面两种示例主要都是父组件向子组件通讯,而经过$emit 实现子组件向父组件通讯。
对于$emit官网上也是解释得很朦胧,我按我本身的理解是这样的:
1
|
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>