组件通信

173 阅读1分钟

父传子

父传子:主要通过 props 来实现的
    具体实现:父组件通过 import 引入子组件,并注册,在子组件标签
上添加要传递的属性,子组件通过 props 接收,接收有两种形式一是通过数
组形式[‘要接收的属性’ ],二是通过对象形式{ }来接收
    对象的形式接收
        props:{
            leftTitle:{
                default:'',
                type:String
            },
            centerTitle:{
                default:'',  //默认值
                type:String,    //类型
                required:true   //是否必传
            },
            rightTitle:{
                default:'',
                type:String,
                required:false,
                validator: function (val) {
                
                },
            }
        },
    
    
},

子传父

子传父:主要通过$emit 来实现
具体实现:子组件通过通过绑定事件触发函数,在其中设置
this.$emit(‘要派发的自定义事件’,要传递的值),$emit 中有两个参数一
是要派发的自定义事件,第二个参数是要传递的值
子组件里:
<template>
    <div>
        <button @click="toParent">点击传到父级</button>
    </div>
</template>
<script>
    export default {
        name: 'child',
        methods: {
            toParent () {
                this.$emit('fromChild', 'child')
            }
        }
    }
</script>
父组件里:
 <template>
  <div>
      <p>子级传过来的值:{{childVal}}</p>
      <child @fromChild="getChild"></child>
  </div>
</template>
<script>
import child from "@/components/child";

export default {
    name: 'parent',
    data () {
        return {
            childVal: ''
        }
    },
    components: {
        child
    },
    methods: {
        getChild (v) {
            this.childVal = v;
        }
    }
}
</script>

兄弟传值

1. src下创建eventBus.js文件
    import Vue from "vue"
    let bus = new Vue;
    export default bus;sendcount
2.发送
    引入eventBus文件import bus from "../eventBus"
    通过bus.$emit"自定义事件名sendCount",传递的值)
3.接收
    mounted(){
        bus.$on("sendCount",(data)=>{
            this.sendData=data
        })
    }

slot插槽

父传子时,在父组件的子组件中
    <h1 slot="a">我是插槽1</h1>
    <p slot="b">我是插槽2</p>
在子组件接收
    <slot name="a"></slot>
    <slot name="b"></slot>