当前位置: 首页 > news >正文

vue.js入门(3)——组件通信

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权威指南》

 

转载于:https://www.cnblogs.com/xulei1992/p/6121974.html

相关文章:

  • Java线程专栏文章汇总(转)
  • 快速破解哈希密文findmyhash
  • JDBC与Hibernate中SQL语句参数设置的顺序问题
  • 数据库备份通用脚本
  • ehcache memcache redis 三大缓存
  • 二十六、Jcreator使用初步
  • 访问修饰符和构造函数
  • YUV Player
  • 盒子模型-怪异模式和标准模式
  • Android开发--Socket通信
  • P1382 光棍组织
  • 1.2 lambda 表达式的语法
  • Lint Code——最多共线的点的个数
  • 【bzoj1433】 ZJOI2009—假期的宿舍
  • 【干货分享】前端面试知识点锦集01(HTML篇)——附答案
  • [PHP内核探索]PHP中的哈希表
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • Apache的80端口被占用以及访问时报错403
  • CSS 提示工具(Tooltip)
  • CSS中外联样式表代表的含义
  • java8-模拟hadoop
  • java多线程
  • JS专题之继承
  • mysql外键的使用
  • nfs客户端进程变D,延伸linux的lock
  • October CMS - 快速入门 9 Images And Galleries
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 从零开始学习部署
  • 理清楚Vue的结构
  • 浏览器缓存机制分析
  • 面试遇到的一些题
  • 判断客户端类型,Android,iOS,PC
  • 如何编写一个可升级的智能合约
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • 原创:新手布局福音!微信小程序使用flex的一些基础样式属性(一)
  • 怎样选择前端框架
  • 国内开源镜像站点
  • ​MPV,汽车产品里一个特殊品类的进化过程
  • ​软考-高级-信息系统项目管理师教程 第四版【第19章-配置与变更管理-思维导图】​
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • "无招胜有招"nbsp;史上最全的互…
  • #Lua:Lua调用C++生成的DLL库
  • #前后端分离# 头条发布系统
  • $$$$GB2312-80区位编码表$$$$
  • $var=htmlencode(“‘);alert(‘2“); 的个人理解
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (AtCoder Beginner Contest 340) -- F - S = 1 -- 题解
  • (动手学习深度学习)第13章 计算机视觉---图像增广与微调
  • (翻译)Entity Framework技巧系列之七 - Tip 26 – 28
  • (附源码)springboot 智能停车场系统 毕业设计065415
  • (附源码)ssm经济信息门户网站 毕业设计 141634
  • (十三)Flask之特殊装饰器详解
  • (一)WLAN定义和基本架构转
  • (原創) 是否该学PetShop将Model和BLL分开? (.NET) (N-Tier) (PetShop) (OO)
  • (转)VC++中ondraw在什么时候调用的