vue 组件通讯

父向子传值
  • Props :父向子组件传值
<template>
<div class="container">
 <child :send="myMsg"></child>
</div>
</template>
  • 子组件接收值
<template>
<div class="child">
  <h2>子组件</h2>
  <strong>{{myMsg}}</strong>
</div>
</template>
<script>
export default {
  props: ['myMsg'],
}
</script>
子向父传值
  • $emit/事件结合: 子向父组件传值
<template>
<div class="child">
  <h2>子组件</h2>
  <p>子组件要发送的消息: </p>
  <p>{{msg}}</p>
  <button @click="send">send</button>
</div>
</template>
<script>
export default {
  data () {
    return {
      msg: '子向父传递的值'
    }
  },
  methods: {
    send () {
      this.$emit('msg', this.msg)
    }
  }
}
</script>

  • 父组件 v-on:xx 接收值
<template>
  <div class="container">
    <h1>父组件</h1>
    <p>从子组件获取的消息:
      <span>{{Msg}}</span>
    </p>
    <child v-on:msg="getMsg"></child>
  </div>
</template>
<script>
import child from './child'
export default {
  data () {
    return {
      Msg: ''
    }
  },
  components: {
    child
  },
  methods: {
    getMsg (e) {
      this.Msg = e
    }
  }
}
</script>
非父子兄弟传值
  • 通过新建一个 busevent.js 文件,使用this.$emit来进行非父子组件传值
  • 在 传值方 引入busevent.js,并通过this.$emit 发布一个方法并携带需要传递的值
  • 在“值”的接收方,引入busevent.js,通过this.$on 来接收传递过来的值
busevent.js
import Vue from 'vue'
const vm = new Vue()
export default vm
b组件(需要传递值的组件)
<template>
  <div class>
    bbb
    <el-button @click="fn">toA</el-button>
  </div>
</template>

<script>
import bus from '../assets/js/busevent'
export default {
  components: {},
  data() {
    return {
      count: 100
    }
  },
  computed: {},
  watch: {},
  methods: {
    fn() {
      bus.$emit('toB', this.count++)
    }
  },
  created() {}
}
</script>
</script>
a组件(接收值)
<template>
  <div class>aaa{{count}}</div>
</template>

<script>
import bus from '../assets/js/busevent'
export default {
  components: {},
  data() {
    return {
      count: 0
    }
  },
  computed: {},
  watch: {},
  methods: {},
  created() {
    bus.$on('toB', data => {
      this.count = data
    })
  }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值