vue 组件间通信

1、父 ===> 子

//父组件:

<template>
  <div class="sign-up-box">
    <sign-up :banding="true" :ishideBanPage="hideBanPage"></sign-up>
  </div>
</template>

    
<script>
import signUp from "@/views/activity/signUp"; //引入子组件
export default {
  data() {
  },
  components: {
    signUp //注册子组件
  },
  methods: {
    // 定义父组件方法
    hideBanPage() {
      console.log('调用父组件方法')
    }
  }
};
</script>

父组件把变量banding 和方法ishideBanPage 传给子组件,子组件接收变量和方法并调用:

//子组件:

<template>
</template>

<script>
export default {
  props: ["banding", "ishideBanPage"], //用props接收父组件传来的值
  data() {
  },
  mounted() {
    //调用
    console.log( this.banding);
    this.ishideBanPage();
  },
  methods: {
  }
};
</script>

2、子 ===> 父 (以下参考文章:https://segmentfault.com/a/1190000010530600?utm_source=tag-newest

通过$on和$emit方法:

*通过$on,$emit*
**父组件代码**
<template>
    <div id="counter-event-example">
      <p>{{ total }}</p>
      <button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</template>
<script>
    import ButtonCounter from './buttonCounter'
    export default {
        name: 'index',
        components: {
            'button-conuter': ButtonCounter
        },
        data () {
            return {
                total: 0
            }
        },
        methods: {
            incrementTotal () {
                this.total++
            }
        }
    }
</script>
**子组件代码**
<template>
    <button @click="incrementCounter">{{counter}}</button>
</template>
<script>
    export default {
        name: 'button-counter',
        data () {
            return {
                counter: 0
            }
        },
        metheds: {
            incrementCounter () {
                this.$emit('increment')
                this.counter++
            }
        }
    }
</script>

 

3、 非父子:(以下方法请教同事嘉伟)

简单情况下我们可以通过使用一个空的Vue实例作为中央事件总线,(这里也可以使用app实例,而不需要新建一个空Vue实例)

**main.js**
let bus = new Vue()
Vue.prototype.bus = bus
//组件A
<template>
  <div>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
    }
  },
  beforeDestroy() {
    //为了确保另一个组件中能够收到信息,信息从beforeDestroy里发送
    this.bus.$emit('userMsg', 'hi'); //向另一个组件发送信息
  }
}
</script>
//组件B
<template>
  <div>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
    }
  },
  created() {
    //接收信息
    this.bus.$on('userMsg', function(msg) {
        console.log(msg) // hi
    })
  },
  beforeDestroy() {
    //销毁
    this.bus.$off('userMsg')
  }
}
</script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值