vue 组件传值(父传子、子传父、兄弟传值)

本文详细介绍了Vue中三种常见的组件间通信方式:父组件向子组件传递数据、子组件向父组件传递数据以及非父子组件间的通信。通过props实现父组件向子组件的单向数据流,利用$emit和v-on处理子组件向父组件的事件传递,最后通过创建公共的event bus实现兄弟组件之间的数据交互。这些方法在实际开发中非常实用。
摘要由CSDN通过智能技术生成

vue 组件传值(父传子、子传父、兄弟传值)

1. vue的父子传值

父组件

<template>
    <div>
        父组件
        <Children :message='msg'/>
    </div>
</template>
<script>
import Children from '../components/AboutCom/Childre.vue'
export default {
    components:{
        Children
    },
    data(){
        return {
            msg:"我是父组件的数据"
        };
    },
};
</script>

子组件

<template>
    <div>
        子组件
        {{message}}
    </div>
</template>
<script>
export default {
    props:{
        message:{
            type:String,
            default:""
        }
    },
};
</script>

在父组件中 在子组件标签中自定义属性 message传递数据

在子组件的props中声明接收 可以设置数据类型、默认值等等

2. vue的子父传值

vue的子父传值 需要用到$emitv-on,在子组件使用$emit 来触发事件 父组件用v-on接收事件函数 函数参数为子组件的数据,接收后在父组件将数据赋值到data中。

<template>
    <div>
        <p>父组件:{{childMsg}}</p>
        
        <Children @childMsg="childMsgFn"/>
    </div>
</template>

<script>
import Children from '../components/AboutCom/Childre.vue'
export default {
    components:{
        Children
    },
    data(){
        return {
            childMsg:""
        };
    },
    methods:{
        chhildMsgFn(val){
            this.childMsg=val
        }
    }
};
</script>
<template>
    <div>
        子组件
        <button @click="msgFn">想父组件传值</button>
    </div>
</template>

<script>
export default {
    methods:{
       msgFn(){
         this.$emit('childMsg','我是子组件的数据')
       }
    }
};
</script>

运行后点击按钮将子组件的数据传到父组件中 

3. vue的兄弟传值(非父子传值)

在兄弟传值中 我们需要先建立一个公共的bus 用来存取

/bus.js

import Vue from 'vue'
export default new Vue()

我们需要将两个组件放在同一个父级组件中。 同时在兄弟两个组件中分别引入 bus.js 在哥哥组件中使用bus.$emit来触发事件 $emit中有两个参数:第一个参数是触发事件的事件名,第二个参数是传递的数据。

这时我们需要在弟弟组件中使用bus.$on监听事件触发 $on同样也有两个参数:第一个也是事件名,第二个则是一个函数, 函数参数是哥哥组件传递的数据。

<template>
    <div>
        我是哥哥
        <button @click="changeFn">传数据给弟弟</button>
    </div>
</template>

<script>
import bus from '../../utils/bus'
export default {
    methods:{
       changeFn(){
         this.$emit('msgFn','我是哥哥')
       }
    }
};
</script>

 

<template>
  <div>我是弟弟{{ message }}</div>
</template>

<script>
import bus from "../../utils/bus";
export default {
  data() {
    return {
      message: "",
    };
  },
  mounted() {
    bus.$on("msgFn", (val) => {
      this.message = val;
    });
  },
};
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值