vue组件数据传值——父传子、子传父、兄弟组件传值

一.父传子props

父组件

子组件接收使用props

注意:props是只读的修改会报错

二.子传父---自定义事件

子组件

 

父组件

 

 

 三.兄弟组件传值---EventBus

新建EventBus.js

import Vue from "vue";
export default  new Vue()

left组件 

 

 

四、整体代码 

index页面

<template>
  <div>
    <header class="header">
      <div>头部</div>
      <div>子组件给父组件的值--{{sonVal}}</div>
    </header>
    <div style="display: flex">
      <left :msg="msg" :val="val"></left>
      <Right @send="getSonVal"></Right>
    </div>
  </div>
</template>

<script>
import Left from "../components/Left";
import Right from "../components/Right";

export default {
  name: "index.vue",
  components:{
    Left,
    Right
  },
  data(){
    return{
      msg:"父传子",
      val:"1000",
      sonVal:""
    }
  },
  methods:{
    getSonVal(val){
      this.sonVal=val
      console.log(val)
    }
  }
}
</script>

<style scoped>
  .header{
    background-color: #da871a;
    width: 100%;
    height: 100px;
    color: #ffffff;
    font-size: 30px;
  }
</style>

Left组件

<template>
  <div class="left">
    <h1>left</h1>
    <div>{{msg}}-----{{val}}------ <button @click="val=123">修改</button></div>
    <div><button @click="sendRight">向兄弟组件传值</button></div>
  </div>
</template>

<script>
import bus from "../utils/EventBus"
export default {
  //只读修改会报错
  props:['msg','val'],
  name: "Left",
  data(){
    return{
      msgLeft:"向兄弟组件传值"
    }
  },
  methods:{
      sendRight() {
          bus.$emit('send',this.msgLeft)
      }
  }
}
</script>

<style scoped>
  .left{
    width: 50%;
    height: 200px;
    color: #ffffff;
    font-size: 15px;
    background-color: cadetblue;
  }
</style>

Right组件 

<template>
  <div class="right">
    <h1>Right</h1>
    <div>子组件给父组件传值{{count}}-----<button @click="send">传值</button></div>
    <div>{{msgFromLeft}}</div>
  </div>
</template>

<script>
import bus from "../utils/EventBus"

export default {
  name: "Right",
  data(){
    return{
      count:0,
      msgFromLeft:''
    }
  },
  created() {
    bus.$on('send',res=>{
      this.msgFromLeft=res
    })
  },
  methods:{
    send(){
      this.count+=1
      this.$emit('send',this.count)
      console.log(this.count)
    }
  }
}
</script>

<style scoped>
.right{
  width: 50%;
  height: 200px;
  color: #ffffff;
  font-size: 15px;
  background-color: #cd7eec;
}
</style>

EventBus

import Vue from "vue";
export default  new Vue()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值