zoukankan      html  css  js  c++  java
  • Vue 组件通信

    父组件 -> 子组件

    props 

    <my-component :date="date"></my-component>

    注意:如果子组件定义props名称使用了驼峰命名,则需要在传值时改成 - 分开,因为html对大小写不敏感,例如

    <my-component :my-date="date"></my-component>

    * 但是在vue单文件组件中貌似是可以使用驼峰写法的

    子组件 -> 父组件

    子组件中直接修改props值可以成功,但是框架会抛出一个错误,所以不推荐

    推荐的做法:在父组件中定义一个修改props的方法,然后子组件调用父组件的方法

    1. 在子组件中直接调用父组件方法修改props值

    this.$parent.change(new Date())

    2. 子组件触发事件,在父组件中捕捉然后执行change方法

    父组件:

    <my-component :my-date="date" @changeDate="change"></my-component>

    子组件:

    this.$emit('changeDate', new Date())

    推荐使用第二种

    子组件 -> 子组件

    这种情况属于两个不相关的子组件之间的通信,我们无法通过props将两者关联起来,两种解决办法:

    1. vuex : 全局状态管理器

    2. 事件总线:EventBus

    定义:本质上就是实例化一个新的Vue对象,这个对象专门负责处理多组件之间的通信

    用法:

    // main.js
    Vue.prototype.$EventBus = new Vue()

    绑定一个eventBus到Vue对象,在页面中通过 on(注册),emit(触发)

    //component1
    this.$EventBus.$on('change', function(param){
      console.log('事件触发',param)
    })
    //component2
    this.$EventBus.$emit('change', 123)
  • 相关阅读:
    python模块搜索路径
    Python数据结构
    Python文件类型
    Python循环语句
    Python条件语句
    python配置文件操作——configparser模块
    python 加密方式(MD5&sha&hashlib)
    python MySQL 获取全部数据库(DATABASE)名、表(TABLE)名
    python sqlite3查看数据库所有表(table)
    027.MFC_映射消息
  • 原文地址:https://www.cnblogs.com/xiaoliwang/p/10631543.html
Copyright © 2011-2022 走看看