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


Posted in Javascript onDecember 02, 2016

本文介绍vue.js组件,具体如下:

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>

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

父组件可以在使用子组件的地方直接用 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>

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

在某个组件的根元素上监听一个原生事件。可以使用 .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>

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

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

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

  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>

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

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

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

$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>

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

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

 5.2.5 非父子组件通信

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

var bus = new Vue()

// 触发组件 A 中的事件
bus.$emit('id-selected', 1)

// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
  // ...
})

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
学习YUI.Ext第五日--做拖放Darg&amp;Drop
Mar 10 Javascript
Js四则运算函数代码
Jul 21 Javascript
jQuery之日期选择器的深入解析
Jun 19 Javascript
JS通过分析userAgent属性来判断浏览器的类型及版本
Mar 28 Javascript
js操作iframe父子窗体示例
May 22 Javascript
js获取滚动距离的方法
May 30 Javascript
如何使用jQuery技术开发ios风格的页面导航菜单
Jul 29 Javascript
angular json对象push到数组中的方法
Feb 27 Javascript
用p5.js制作烟花特效的示例代码
Mar 21 Javascript
剖析Angular Component的源码示例
Mar 23 Javascript
Vue 实现复制功能,不需要任何结构内容直接复制方式
Nov 09 Javascript
Node.js 中判断一个文件是否存在
Aug 24 Javascript
javascript实现鼠标点击页面 移动DIV
Dec 02 #Javascript
jquery对所有input type=text的控件赋值实现方法
Dec 02 #Javascript
bootstrap使用validate实现简单校验功能
Dec 02 #Javascript
在网页中插入百度地图的步骤详解
Dec 02 #Javascript
PHP获取当前页面完整URL的方法
Dec 02 #Javascript
jQuery插件fullPage.js实现全屏滚动效果
Dec 02 #Javascript
jquery 追加元素append、prepend、before、after用法与区别分析
Dec 02 #Javascript
You might like
PHP数组实例详解
2016/06/26 PHP
PHP实现微信公众号验证Token的示例代码
2019/12/16 PHP
js GridView 实现自动计算操作代码
2009/03/25 Javascript
最短的IE判断代码
2011/03/13 Javascript
利用js正则表达式验证手机号,email地址,邮政编码
2014/01/23 Javascript
JQuery中Bind()事件用法分析
2015/05/05 Javascript
javascript数据结构之双链表插入排序实例详解
2015/11/25 Javascript
Bootstrap入门书籍之(零)Bootstrap简介
2016/02/17 Javascript
WordPress 单页面上一页下一页的实现方法【附代码】
2016/03/10 Javascript
浅析函数声明和函数表达式——函数声明的声明提前
2016/05/03 Javascript
jQuery配合coin-slider插件制作幻灯片效果的流程解析
2016/05/13 Javascript
bootstrap提示标签、提示框实现代码
2016/12/28 Javascript
jQuery移除或禁用html元素点击事件常用方法小结
2017/02/10 Javascript
对vuejs的v-for遍历、v-bind动态改变值、v-if进行判断的实例讲解
2018/08/27 Javascript
在JavaScript中如何访问暂未存在的嵌套对象
2019/06/18 Javascript
Vue解析剪切板图片并实现发送功能
2020/02/04 Javascript
JavaScript中window和document用法详解
2020/07/28 Javascript
[07:40]DOTA2每周TOP10 精彩击杀集锦vol.4
2014/06/25 DOTA
Python随机生成一个6位的验证码代码分享
2015/03/24 Python
详解如何在python中读写和存储matlab的数据文件(*.mat)
2018/02/24 Python
Python学生信息管理系统修改版
2018/03/13 Python
Python使用Dijkstra算法实现求解图中最短路径距离问题详解
2018/05/16 Python
Python实现繁?转为简体的方法示例
2018/12/18 Python
Python下简易的单例模式详解
2019/04/08 Python
Python pandas自定义函数的使用方法示例
2019/11/20 Python
Python命名空间及作用域原理实例解析
2020/08/12 Python
微信小程序实现可实时改变转速的css3旋转动画实例代码
2018/09/11 HTML / CSS
使用CSS3的box-sizing属性解决div宽高被内边距撑开的问题
2016/06/28 HTML / CSS
利用css3如何设置没有上下边的列表间隔线
2017/07/03 HTML / CSS
Luxplus荷兰:以会员价购买美容产品等,独家优惠
2019/08/30 全球购物
俄罗斯最大的在线手表商店:Bestwatch.ru
2020/01/11 全球购物
行政专员岗位职责
2014/01/02 职场文书
诚信承诺书范文
2014/03/27 职场文书
小学生纪念九一八事变演讲稿
2014/09/14 职场文书
村官2015年度工作总结
2015/10/14 职场文书
Java多线程并发FutureTask使用详解
2022/06/28 Java/Android