vue组件之间传值

vue组件之间通信方式有三种: 父传子、子传父、兄弟组件相互传值

1.父组件向子组件传值(通过props)

  1. 在父组件中通过import引入子组件并组册
  2. 在子组件标签身上添加自定义属性将要传递的值绑定到自定义属性上
  3. 一定要加v-bind(简写:)否则会将字符串传过去
父组件
<template>
  <div id="app">
    <HelloWorld :userMsg="userInfo"/>
  </div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import Right from './components/Right.vue'

export default {
  name: 'App',
  data() {
    return {
      msg: '父组件里面的值',
    }
  },
  components: { HelloWorld }
}
</script>

子组件
<template>
  <div>
      <h1>{{ AppMsg }}</h1>
  </div>
</template>

通过props接收父组件传过来的值

<script>
export default {
  name: 'HelloWorld',
  props: ['AppMsg']
}
</script>

2.子组件向父组件传值(通过自定义事件)

  1. 使用$emit
  2. 通过自定义事件方法接收
子组件
<template>
  <div>
    <h1>子组件向父组件传输数据</h1>
    <button @click="onShow">点我传值</button>
  </div>
</template>
<script>
export default {
  name: 'Right',
  data() {
    return {
      info: '我是子组件里面的数据'
    }
  },
  methods: {
    onShow() {
      this.$emit('receive', this.info)
    }
  }
}
</script>
父组件
<template>
  <div id="app">
    <Right @receive="getInfo"></Right>
  </div>
</template>

<script>
import Right from './components/Right.vue'

export default {
  name: 'App',
  data() {
    return {
      msg: '',
    }
  },
  methods: {
    getInfo(val) {
      this.msg = val
    }
  },
  components: { Right }
}
</script>

3.兄弟组件之间的传值(通过eventBus)

  1. 新建eventBus.js文件
  2. 导入vue实例
  3. 在兄弟组件导入evenBus.js
  4. 发送数据使用bus.$emit()
  5. 接收数据使用bus.$on()
  6. 通过ceated()监听自定义事件

eventBus.js

import Vue from 'vue'

export default new Vue()
兄弟组件A(发数据)
<template>
  <div>
    <button @click="send">点我给兄弟组件传值</button>
  </div>
</template>
<script>
import bus from '../eventBus'
export default {
  name: 'Right',
  data() {
    return {
      str: '是兄弟就来砍我'
    }
  },
  methods: {
    send() {
      bus.$emit('share', this.str)
    }
  }
}
</script>

兄弟组件B(接收数据)
<template>
  <div>
      <h1>{{ msgAtBrothers }}</h1>
  </div>
</template>
<script>
import bus from '../eventBus'
export default {
  name: 'HelloWorld',
  data() {
    return {
      msgAtBrothers: ''
    }
  },
  created() {
    bus.$on('share', (res) => {
      this. msgAtBrothers = res
    })
  },
}
</script>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值