zoukankan      html  css  js  c++  java
  • 非父子组件通过事件传值-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>

      

  • 相关阅读:
    hdu_1072_Nightmare(BFS)
    hdu_4826_Labyrinth_2014百度之星(dp)
    hdu_4823_Energy Conversion
    hdu_3063_Play game
    hdu_3062_Party(2-SAT)
    5、1 部署
    klayge 4.2.0 编译vc9
    数据延迟加载
    指令 scope
    指令 作用域
  • 原文地址:https://www.cnblogs.com/yuyedaocao/p/11981638.html
Copyright © 2011-2022 走看看