vue组件消息传递(子传父 父传子 兄弟间传值)

这篇博客探讨了在Vue中如何实现父子组件间的通信,利用pubsub-js库实现发布订阅模式,以及组件间通过$bus传递数据的方法。文章详细展示了代码示例,包括one组件、App组件和two组件的交互过程,涉及事件监听和触发,以及数据的传递和接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看图

在这里插入图片描述

one

<template>
    <div>
        <img :src='imgurl' width=450 height=300/> 子给传父的图片
        <App><h3>{{fuchuanzi}}</h3></App>
        <el-button @click="toTwo()" type="success">给two传值</el-button>
    </div>
</template>

<script>
import PubSub from 'pubsub-js' //引入pubsub.js 他是一种发布订阅者模式,父子都要引入
export default {
  name: "VueOne",
  props: {
    fuchuanzi: String //这边接收到直接可以插值表达式应用
  },
  data() {
    return {
      imgurl: require("../assets/aaaa.jpg"),
    };
  },
  mounted() {
      PubSub.subscribe("hello", (mes, data) => {
        alert("子收到了一条消息:"+data);
      });
  },
  methods: {
    toTwo(){
      this.$bus.$emit('to-two', '您好兄弟two')
    }
  }
};
</script>

<style lang="scss" scoped>
</style>

app

<template>
  <div id="app">
    <HelloWorld msg="这是HelloWorld的部分"/>
    <div id="user" width="500px">
      <h1>这是two部分</h1>
      <Two></Two>
    </div>

    <div id="one" width="500px">
      <h1>这是one部分</h1>
    <one :fuchuanzi="fuchuanzi1"/>
    请输入发布的内容:<input v-model="msg"/>
    <el-button @click="zzz()" type="danger">父亲发布消息</el-button>

    </div>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import Two from './components/Two.vue'
import One from './components/One.vue'
import PubSub from 'pubsub-js' //引入pubsub.js 他是一种发布订阅者模式,父子都要引入
export default {
  name: 'App',
  components: {
    HelloWorld,
    Two,
    One,
  },
  props: {
    sayHello: Function
  },
  data() {
    return {
      fuchuanzi1: "父传给子的一段消息",
      msg: ""
    }
  },
  methods: {
    zzz(){
        PubSub.publish('hello', this.msg)
    }
    },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
#user {
  background: pink;
}
#one {
  background: yellowgreen;
}
</style>

two

<template>
    <div>
        <h1>{{msg}}</h1>
        <el-button @click="hello()" type="success">点我试试!</el-button>
    </div>
</template>

<script>
export default {
    name: 'Two',
    data() {
        return {
            msg: '我是一个变量 子的变量传到父'
        };
    },

    methods: {
        hello() {
            alert('子的方法在父应用')
        }
    },
    mounted(){
        this.$bus.$on('to-two', function (data) {
      console.log(data,'哥哥two组件传过来的数据')
    })
    }

};
</script>

<style lang="scss" scoped>

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值