• vue EventHub事件派发和广播、发射与接收(可实现页面传值和非父子组件传值)


      由于 vue2.0 移除了1.0中的$dispatch 和$broadcast 这两个组件之间通信传递数据的方法,官方给出的最简单的升级建议是使用集中的事件处理器,而且也明确说明了 一个空的vue实例就可以做到,因为Vue 实例实现了一个事件分发接口。

      vue2.0中可以使用 $emit, $on, $off 分别来分发、监听、取消监听事件。

    1、在初始化web app的时候,给data添加一个 名字为 eventhub 的空vue对象,就可以在任何组件都可以调用事件发射接收的方法了,在main.js中添加:

    new Vue({
      el: '#app',
      router,
      data: {
        eventHub: new Vue()
      },
      render: h => h(App),
      components: { App },
      template: '<App/>'
    })

      这个时候你就可以一劳永逸了,在任何组件都可以调用事件发射和接受的方法了

    2、在home组件内调用事件接受参数($on监听)

    mounted(){
        this.$root.eventHub.$on('事件名称', (data)=>{
          console.log('接受到的参数:'+data)
        } )
      },

    3、在adress组件内调用事件触发 ($emit分发)

    //通过this.$root.eventHub获取此对象
    this.$root.eventHub.$emit('事件名称', '这里是参数,选中后的地址')

    4、在home组件中销毁($off取消)

    beforeDestroy () {
      this.$root.eventHub.$off('事件名称')
    },

    5、拓展

      在stackoverflow 发现一个更加简洁的方法,因为本质上vue是一个js对象,我们想保存一个全局对象,只需要在Vue的prototype上面增加一个属性即可。

      本质上所有Vue组件都是继承全局的Vue,只要在初始化Vue对象之前给原生Vue对象prototype增加属性,那样所有的组件(因为都是继承自它的实例)都可以访问到这个属性。

    // 在初始化Web app 之前 加上这样一句:
    Vue.prototype.$eventHub= Vue.prototype.$eventHub ||  new Vue()

      当然我们可以定义其他的全局变量。比如当前app的系统配置文件,名字为sysconfig.json,你可以这样定义

    Vue.prototype.$config =Vue.prototype.$config||require('path/sysconfig.json')

      这样我们在组件内部就可以直接调用$eventHub 和 $config对象了。 比如在mounted函数里面直接 console.log($config.yourKey)

      刚才看到了webpack的插件里面有一个definePlugin 它可以帮我们定义全局的常量。

      如何使用,很简单但是更好,我们不用去修改Vue对象:

    new webpack.DefinePlugin({
      CONFIG: require('path/sysconfig.json')
    });

      然后我们也可以在全局内使用CONFIG对象了。

  • 相关阅读:
    Hierarchy Query (Connect by) and ORA600 ([kkqcbydrv:1])
    The Steps to Create a New Oracle Database
    Change Schema Name (II)
    [转]The differences between V$UNDOSTAT and V$ROLLSTAT
    【Oracle Mgmt】Oracle Character Semantics (NLS_LENGTH_SEMANTICS) and etc...
    [Oracle Mgmt]About Oracle Password File
    Show parameter & Table Not exists
    RMAN Recovery Window and Redundancy Concept
    [PLSQL]Are you sure it will be definitely random? (DBMS_RANDOM.SEED)
    IOT, Secondary Index and Mapping Table
  • 原文地址:https://www.cnblogs.com/goloving/p/13942752.html
Copyright © 2020-2023  润新知