5.2 组件通信

  尽管子组件可以用this.$parent访问它的父组件及其父链上任意的实例,不过子组件应当避免直接依赖父组件的数据,尽量显式地使用 props 传递数据。另外,在子组件中修改父组件的状态是非常糟糕的做法,因为:

  1. 这让父组件与子组件紧密地耦合;
  2. 只看父组件,很难理解父组件的状态。因为它可能被任意子组件修改!理想情况下,只有组件自己能修改它的状态。

  每个Vue实例都是一个事件触发器:

  • $on()——监听事件。
  • $emit()——把事件沿着作用域链向上派送。(触发事件)
  • $dispatch()——派发事件,事件沿着父链冒泡。
  • $broadcast()——广播事件,事件向下传导给所有的后代。

5.2.1 监听与触发

  v-on监听自定义事件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!--子组件模板-->
<template id="child-template">
<input v-model="msg" />
<button v-on:click="notify">Dispatch Event</button>
</template>
<!--父组件模板-->
<div id="events-example">
<p>Messages: {{ messages | json }}</p>
<child v-on:child-msg="handleIt"></child>
</div>
</body>
<script src="js/vue.js"></script>
<script>
// 注册子组件
// 将当前消息派发出去
Vue.component('child', {
template: '#child-template',
data: function (){
return { msg: 'hello' }
},
methods: {
notify: function() {
if(this.msg.trim()){
this.$dispatch('child-msg',this.msg);
this.msg = '';
}
}
}
})
// 初始化父组件
// 在收到消息时将事件推入一个数组中
var parent = new Vue({
el: '#events-example',
data: {
messages: []
},
methods:{
'handleIt': function(){
alert("a");
}
}
})
</script>
</html>

  父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</body>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
</script>
</html>

  在某个组件的根元素上监听一个原生事件。可以使用 .native 修饰v-on 。例如:

<my-component v-on:click.native="doTheThing"></my-component>

5.2.2 派发事件——$dispatch()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<p>Messages: {{ messages | json }}</p>
<child-component></child-component>
</div>
<template id="child-component">
<input v-model="msg" />
<button v-on:click="notify">Dispatch Event</button>
</template> <script src="js/vue.js"></script>
<script>
// 注册子组件
Vue.component('child-component', {
template: '#child-component',
data: function() {
return {
msg: ''
}
},
methods: {
notify: function() {
if (this.msg.trim()) {
this.$dispatch('child-msg', this.msg)
this.msg = ''
}
}
}
}) // 初始化父组件
new Vue({
el: '#app',
data: {
messages: []
},
events: {
'child-msg': function(msg) {
this.messages.push(msg)
}
}
})
</script>
</body>
</html>

  1. 子组件的button元素绑定了click事件,该事件指向notify方法
  2. 子组件的notify方法在处理时,调用了$dispatch,将事件派发到父组件的child-msg事件,并给该该事件提供了一个msg参数
  3. 父组件的events选项中定义了child-msg事件,父组件接收到子组件的派发后,调用child-msg事件。

5.2.3 广播事件——$broadcast()

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<input v-model="msg" />
<button v-on:click="notify">Broadcast Event</button>
<child-component></child-component>
</div> <template id="child-component">
<ul>
<li v-for="item in messages">
父组件录入了信息:{{ item }}
</li>
</ul>
</template> <script src="js/vue.js"></script>
<script>
// 注册子组件
Vue.component('child-component', {
template: '#child-component',
data: function() {
return {
messages: []
}
},
events: {
'parent-msg': function(msg) {
this.messages.push(msg)
}
}
})
// 初始化父组件
new Vue({
el: '#app',
data: {
msg: ''
},
methods: {
notify: function() {
if (this.msg.trim()) {
this.$broadcast('parent-msg', this.msg)
}
}
}
})
</script>
</body>
</html>

  和派发事件相反。前者在子组件绑定,调用$dispatch派发到父组件;后者在父组件中绑定,调用$broadcast广播到子组件。

5.2.4 父子组件之间的访问

  • 父组件访问子组件:使用$children或$refs
  • 子组件访问父组件:使用$parent
  • 子组件访问根组件:使用$root

$children:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div> <template id="parent-component">
<child-component1></child-component1>
<child-component2></child-component2>
<button v-on:click="showChildComponentData">显示子组件的数据</button>
</template> <template id="child-component1">
<h2>This is child component 1</h2>
</template> <template id="child-component2">
<h2>This is child component 2</h2>
</template>
<script src="js/vue.js"></script>
<script>
Vue.component('parent-component', {
template: '#parent-component',
components: {
'child-component1': {
template: '#child-component1',
data: function() {
return {
msg: 'child component 111111'
}
}
},
'child-component2': {
template: '#child-component2',
data: function() {
return {
msg: 'child component 222222'
}
}
}
},
methods: {
showChildComponentData: function() {
for (var i = 0; i < this.$children.length; i++) {
alert(this.$children[i].msg)
}
}
}
}) new Vue({
el: '#app'
})
</script>
</body>
</html>

  $ref可以给子组件指定索引ID:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div> <template id="parent-component">
<!--<child-component1></child-component1>
<child-component2></child-component2>-->
<child-component1 v-ref:cc1></child-component1>
<child-component2 v-ref:cc2></child-component2>
<button v-on:click="showChildComponentData">显示子组件的数据</button>
</template> <template id="child-component1">
<h2>This is child component 1</h2>
</template> <template id="child-component2">
<h2>This is child component 2</h2>
</template>
<script src="js/vue.js"></script>
<script>
Vue.component('parent-component', {
template: '#parent-component',
components: {
'child-component1': {
template: '#child-component1',
data: function() {
return {
msg: 'child component 111111'
}
}
},
'child-component2': {
template: '#child-component2',
data: function() {
return {
msg: 'child component 222222'
}
}
}
},
methods: {
showChildComponentData: function() {
// for (var i = 0; i < this.$children.length; i++) {
// alert(this.$children[i].msg)
// }
alert(this.$refs.cc1.msg);
alert(this.$refs.cc2.msg);
}
}
})
new Vue({
el: '#app'
})
</script>
</body>
</html>

  效果与$children相同。

  $parent:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div> <template id="parent-component">
<child-component></child-component>
</template> <template id="child-component">
<h2>This is a child component</h2>
<button v-on:click="showParentComponentData">显示父组件的数据</button>
</template> <script src="js/vue.js"></script>
<script>
Vue.component('parent-component', {
template: '#parent-component',
components: {
'child-component': {
template: '#child-component',
methods: {
showParentComponentData: function() {
alert(this.$parent.msg)
}
}
}
},
data: function() {
return {
msg: 'parent component message'
}
}
})
new Vue({
el: '#app'
})
</script>
</body>
</html>

  如开篇所提,不建议在子组件中修改父组件的状态。

5.2.5 非父子组件通信

  有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的 Vue 实例作为中央事件总线:

var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
// ...
})

  在更多复杂的情况下,可以考虑使用专门的 状态管理模式

参考:http://www.cnblogs.com/keepfool/p/5637834.html

《vue.js权威指南》

vue.js入门(3)——组件通信的更多相关文章

  1. 转: Vue.js——60分钟组件快速入门(上篇)

    转自: http://www.cnblogs.com/keepfool/p/5625583.html Vue.js——60分钟组件快速入门(上篇)   组件简介 组件系统是Vue.js其中一个重要的概 ...

  2. Vue.js学习 Item11 – 组件与组件间的通信

    什么是组件? 组件(Component)是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能.在有 ...

  3. vue.js 精学组件记录

    组件需要注册后才可以使用. Vue.component('my-component',{ template:'<div>这是组件内容</div>' }): 局部注册组件 var ...

  4. Vue.js 的精髓——组件

    开篇:Vue.js 的精髓——组件 写在前面 Vue.js,无疑是当下最火热的前端框架 Almost,而 Vue.js 最精髓的,正是它的组件与组件化.写一个 Vue 工程,也就是在写一个个的组件. ...

  5. Vue.js 入门:从零开始做一个极简 To-Do 应用

    Vue.js 入门:从零开始做一个极简 To-Do 应用 写作时间:2019-12-10版本信息:Vue.js 2.6.10官网文档:https://cn.vuejs.org/ 前言  学习 Vue ...

  6. Vue.js 入门教程

    Vue.js 入门教程:https://cn.vuejs.org/v2/guide/index.html

  7. 免费的 Vue.js 入门与进阶视频教程

    这是我免费发布的高质量超清「Vue.js 入门与进阶视频教程」. 全网最好的.免费的 Vue.js 视频教程,课程基于 Vue.js 2.0,由浅入深,最后结合实际的项目进行了最棒的技术点讲解,此课程 ...

  8. vue.js相关UI组件收集

    内容 UI组件 开发框架 实用库 服务端 辅助工具 应用实例 Demo示例 ###UI组件 element ★9689 - 饿了么出品的Vue2的web UI工具套件 Vux ★6927 - 基于Vu ...

  9. Vue.js入门(一)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta htt ...

  10. Vue.js的动态组件模板

    组件并不总是具有相同的结构.有时需要管理许多不同的状态.异步执行此操作会很有帮助. 实例: 组件模板某些网页中用于多个位置,例如通知,注释和附件.让我们来一起看一下评论,看一下我表达的意思是什么.评论 ...

随机推荐

  1. xenu工具介绍

    Xenu Link Sleuth 也许是你所见过的最小但功能最强大的检查网站死链接的软件了.你可以打开一个本地网页文件来检查它的链接,也可以输入任何网址来检查.它可以分别列出网站 的活链接以及死链接, ...

  2. 开篇&TexturePacker打出图集给UGUI使用

    开篇: 前段时间,网上流出了一套手游源码,本想着把服务器端搭一下,给自己认识小伙伴们调试着把这套源码学习一下.于是就买一个阿里云服务器,可是花了几天时间,就是run不起来了啊.还好网上已经有人搭出来了 ...

  3. iOS 开发小结

    一,经历 1> 在编写以前有过的类似的新功能时,如果以前的开发人员没有写明明确的注释和开发需求,一定要仔细阅读所有代码,每一句代码都有它存在的意义. 2> 例如,只以为是[self.ful ...

  4. Linux watch 监控系统状态

    1.linux下watch命令的基本用法 # watch --helpUsage: watch [-dhntv] [--differences[=cumulative]] [--help] [--in ...

  5. 【Go语言】学习资料

    这段时间一直在看Go语言,6月3日Apple发布了swift发现里面竟然也有许多Go语言的影子,截至现在每天都在感觉到Go语言的强大.确实值得一学 今天在这里给园友们推荐一些Go语言的学习资料 网站 ...

  6. [LintCode] Count and Say 计数和读法

    The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221 ...

  7. [CareerCup] 15.2 Renting Apartment II 租房之二

    Write a SQL query to get a list of all buildings and the number of open requests (Requests in which ...

  8. 重命名PDF打印文件名

    Odoo系统默认打印出来的PDF文件都是以当前文档模型对象对应的模板文件名命名的,对用户来说,这样的命名很不友好. 我们希望能够将打印出来的文件名以单号命名,下面是实现这种目的的方法. 在report ...

  9. C# 截取字符串

    1.根据单个分隔字符用split截取 例如 string st="GT123_1"; string[] sArray=st.split("_"); 即可得到sA ...

  10. .NET 页面间传值的几种方法

    1. QueryString 这是最简单的传值方式,但缺点是传的值会显示在浏览器的地址栏中且不能传递对象,只适用于传递简单的且安全性要求不高的数值. 传递: location.href="W ...