Vue组件高级通讯之$children与$parent
一、$children组件属性
官方介绍:当前实例的直接子组件。需要注意 $children 并不保证顺序
,也不是响应式的。
即$children是组件自带的属性,它可以获取到当前组件的子组件,并以数组的形式返回。
二、$parent
官方介绍:指定已创建的实例之父实例,在两者之间建立父子关系。子实例可以用 this.$parent 访问父实例
,子实例被推入父实例的 $children 数组中。
如果组件没有父组件,他的$parent为undefined
,App组件(根组件)的$parent不是undefined,也不是App本身。
如果组件有多个父亲,但是$parent只能找到一个,不知道是不是bug,建议慎用。
注意:节制地使用$parent 和 $children
它们的主要目的是作为访问组件的应急方法。更推荐用 props 和 events 实现父子组件通信。
三、小例子:通过借钱案例加深理解
Father.vue
<template> <div> <h2>父亲金钱:{{ fatherMoney }}</h2> <button @click="jieqian">问子女借钱100元</button> <Son></Son> <Daughter></Daughter> </div> </template> <script> import Son from "./Son"; import Daughter from "./Daughter"; export default { components: { Son, Daughter, }, data() { return { fatherMoney: 0, }; }, methods: { jieqian() { this.fatherMoney += 100 * 2; this.$children.forEach((dom) => { dom.childrenMoney -= 100; }); }, }, }; </script> <style></style>
Son
<template> <div style="background-color: #999"> <h2>儿子金钱:{{ childrenMoney }}</h2> <button @click="giveFatherMoney(100)">给父亲100</button> </div> </template> <script> export default { name: "Son", data() { return { childrenMoney : 20000, }; }, methods: { giveFatherMoney(money) { this.$parent.fatherMoney += money; this.childrenMoney -= money; }, }, }; </script> <style> </style>
Daughter
<template> <div style="background-color: #999"> <h2>女儿金钱:{{ childrenMoney }}</h2> <button @click="giveFatherMoney(100)">给父亲100</button> </div> </template> <script> export default { name: "Daughter", data() { return { childrenMoney : 20000, }; }, methods: { giveFatherMoney(money) { this.$parent.fatherMoney += money; this.childrenMoney -= money; }, }, }; </script> <style> </style>
以上就是Vue组件高级通讯之$children与$parent的详细内容,更多关于Vue组件通讯$children $parent的资料请关注脚本之家其它相关文章!
相关文章
解决Vue中引入swiper,在数据渲染的时候,发生不滑动的问题
今天小编就为大家分享一篇解决Vue中引入swiper,在数据渲染的时候,发生不滑动的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-09-09vue使用$attrs和$listeners多级组件嵌套传递数据
这篇文章主要为大家介绍了vue使用$attrs和$listeners多级组件嵌套传递数据示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-08-08详解vue-video-player使用心得(兼容m3u8)
这篇文章主要介绍了详解vue-video-player使用心得(兼容m3u8),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-08-08Vue.js条件渲染和列表渲染以及Vue中key值的内部原理
这篇文章主要介绍了Vue.js条件渲染和列表渲染,以及Vue中key值的内部原理,文中有详细的代码示例,感兴趣的同学可以参考阅读2023-04-04
最新评论