• 非父子组件通过事件传值-vue


    1、创建中央事件总线:额外的 new Vue()
    2、$emit 触发事件
    3、$on 监听事件

    在使用组件的文件中:

    <template>
      <div>
         <x-test  :bus="bus"></x-test>
         <x-right :bus="bus"></x-right>
      </div>
    </template>
    import Vue from 'vue'
    export default {
      data () {
         return {
           username: 'xissazi',
           bus: new Vue()
         }
      }
    }

    子组件 <x-right>触发事件:

    <template>
      <div>
        <button @click="add">增加</button>
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          num: 1
        }
      },
      props: ['bus'],
      methods: {
        add: function () {
          let n = this.num++
          this.bus.$emit('otherEvent', n)
        }
      }
    }
    </script>

    子组件 <x-test>:

    <template>
      <div>
        {{ num }}
      </div>
    </template>
    <script>
    export default {
      data () {
        return {
          num: 0
        }
      },
      props:['name', 'bus'],
      mounted() {
        let that = this
        this.bus.$on('otherEvent', function(val){
          that.num = val
        })
      }
    }
    </script>

      

  • 相关阅读:
    wepack使用
    js 原型链
    react 生命周期
    settimeout--原来定时器是有三个及以上参数的
    我所未知的 typeof 现象
    js 里面的 function 与 Function
    ECMAScript 对象类型
    js阻碍DOM加载
    面试问题与心得
    Java IO 乱码
  • 原文地址:https://www.cnblogs.com/yuyedaocao/p/11981638.html
Copyright © 2020-2023  润新知