vue传值总结

一、父组件 向 子组件传值

1、父组件调用子组件的时候,在子组件身上绑定动态属性
<template>
    <div>
        <Child :title="title"> </Child>//子组件
    </div>
</template>
2、在对应的子组件中,通过props属性接收传递过来的值
props:{
        title:{
            type:String,
            default:'我是标题'
        }
}
3、在子组件中使用该值
<div>{{title}}</div>

二、父组件 主动获取 子组件的数据和方法

1、父组件调用子组件的时候,在子组件身上定义ref
<template>
    <div>
        <Child ref="childId"> </Child>//子组件
        //注:ref相当于dom里的id,在js里边调用方式是:this.$refs.childId
    </div>
</template>
2、在父组件调用子组件的数据和方法
this.$refs.childId.数据或方法

三、子组件 向 父组件中传值

总结:

在子组件中:

1.定义一个事件和方法toParent,来向父组件传值
2.在这个toParent方法中,使用$emit发送数据(也叫做广播数据)

this.$emit('任意发送数据的名称',要发射的数据)
在父组件中:

1.在契合点的位置,定义自定义事件和方法 (和子组件的方法名保持一致)

子组件
//子组件Child.vue
<template>
    <div>
        <button @click="toParent">降价</button></p>ildId
    </div>
</template>

子组件的methods:

toParent(count){
      this.$emit('toParent',this.count)
}

// toParent是传递给父组件的事件,父组件触发、并相应这个方法
// this.data 传递给父组件的参数,,在父组件中,可以对和这个参数进行相应操作

父组件Parent.vue

<template>
   <div>
       <Child  @toParent="toParent"></Child>
   </div>
</template>

父组件的methods:

toParent(count) {
      this.price = count + 10;
     
    }

四、兄弟组件通信

1.定义一个公共文件 eventBus.js
import Vue from 'vue'
export default new Vue()
2.在需要通信的同级组件中分别引入eventBus.js文件
import eventBus from '../eventBus.js'
3.发出数据的组件 Son1.vue
<button @click="emitSon2">发出数据</button>

//方法
methods:{
    emitSon2(){
        eventBus.$emit('toSon2',this.name)
    }
}
4.接收数据的组件 son2.vue
mounted:{
    eventBus.$on("toSon2", (data) => {
          console.log(data)
    });
}

相关推荐