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

本文介绍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>

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

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

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

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索vue.js
, vue
, vuejs
, 组件通信
, 组件和组件通信
组件之间通信
vue.js组件详解、vue组件详解、vue 组件入门、vue 组件、vue ui组件库,以便于您获取更多的相关知识。

时间: 2024-07-28 12:42:27

vue.js入门(3)——详解组件通信_javascript技巧的相关文章

vue.js入门教程之基础语法小结_javascript技巧

前言 Vue.js是一个数据驱动的web界面库.Vue.js只聚焦于视图层,可以很容易的和其他库整合.代码压缩后只有24kb. 以下代码是Vue.js最简单的例子, 当 input 中的内容变化时,p 节点的内容会跟着变化. <!-- html --> <div id="demo"> <p>{{message}}</p> <input v-model="message"> </div> new

Vue.js一个文件对应一个组件实践_javascript技巧

这方面官网给的示例是需要工具来编译的,但是nodejs又没有精力去学,只好曲线救国.VueJS的作者在另一个网站有一篇文章讲到可以用jQuery.getScript或RequireJS实现组件,却没有给示例,于是自己摸索出了一种方法. 用到的工具: vue.js --- 0.12.+ (需要0.12中async component支持) require.js text.js --- RequireJS text plugin https://github.com/requirejs/text 文

Vue.JS入门教程之事件监听_javascript技巧

你可以使用 v-on 指令来绑定并监听 DOM 事件.绑定的内容可以是一个当前实例上的方法 (后面无需跟括号) 或一个内联表达式.如果提供的是一个方法,则原生的 DOM event 会被作为第一个参数传入,同时这个 event 会带有 targetVM 属性,指向触发该事件的相应的 ViewModel: <div id="demo"> <a v-on="click: onClick">触发一个方法函数</a> <a v-on

Vue.JS入门教程之处理表单_javascript技巧

本文实例为大家分享了Vue.JS表单处理的相关内容,供大家参考,具体内容如下 基本用法 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.m

深入探讨Vue.js组件和组件通信_javascript技巧

基本是按照官网的 Guide 全部梳理了一遍:http://vuejs.org/guide/index.html 这里我们以一个 Todo List 应用为例来把相关的只是都串起来,这篇里面的全部代码都在github上 https://github.com/lihongxun945/vue-todolist  Vue 实例 一个 Vue 应用是由一个 root vue instance 引导启动的,而 Vue instance 是这么创建的: var vm = new Vue({ // opti

详解Bootstrap按钮_javascript技巧

描述 Bootstrap Button(按钮)JavaScript 插件允许您加强按钮的功能.您可以控制按钮的状态,也可以为组件创建按钮组,比如工具条. 什么是必需的 您必须引用 jquery.js 和 bootstrap-button.js - 这两个 JavaScript 文件.它们都位于 docs/assets/js 文件夹内. 如何使用它 您可以不编写任何 JavaScript 只通过标记使用该插件,也可以通过 JavaScript 启用按钮. Bootstrap 提供了一些选项来定义按

详解Bootstrap插件_javascript技巧

在前面 布局组件 章节中所讨论到的组件仅仅是个开始.Bootstrap 自带 12 种 jQuery 插件,扩展了功能,可以给站点添加更多的互动.即使您不是一名高级的 JavaScript 开发人员,您也可以着手学习 Bootstrap 的 JavaScript 插件.利用 Bootstrap 数据 API(Bootstrap Data API),大部分的插件可以在不编写任何代码的情况被触发. 站点引用 Bootstrap 插件的方式有两种: 单独引用:使用 Bootstrap 的个别的 *.j

微信公众平台开发教程(五)详解自定义菜单_javascript技巧

一.概述: 如果只有输入框,可能太简单,感觉像命令行.自定义菜单,给我们提供了很大的灵活性,更符合用户的操作习惯.在一个小小的微信对话页面,可以实现更多的功能.菜单直观明了,不仅能提供事件响应,还支持URL跳转,如果需要的功能比较复杂,我们大可以使用URL跳转,跳转至我们的网页即可. 注意:自定义菜单,只有服务号才有此功能 接着我们详细介绍,如何实现自定义菜单? 二.详细步骤: 1.首先获取access_token access_token是公众号的全局唯一票据,公众号调用各接口时都需使用acc

JavaScript 深层克隆对象详解及实例_javascript技巧

 JavaScript 深层克隆对象 今天做项目,有个需求需要用到深层克隆对象,并且要求在原型链上编程 于是心血来潮索性来复习一下这个知识点,在网上找了相应的知识, 克隆对象,这名词看着高大上,其实也没什么,便是拷贝一个长的一模一样的对象 也许有初学的小伙伴在想,那还不简单么,so easy var obj1 = {name: 'payen'}; var obj2 = obj1; 这可并不是克隆对象,obj1和obj2根本就是同一个对象, 他俩指向同一个内存地址空间,拿到了同样的一个小房子 这是