vue组件通信(父子之间,兄弟之间)

一、父组件向子组件传值

1、在父组件中引入需要通信的子组件

import Son from "./components/Son";

2、在父组件的components中注册该子组件

components: {
    Son
  }

3、在父组件的template中使用子组件

<Son></Son>

4、将需要传递给子组件的值通过v-bind

<Son :price="price"></Son>

//  此处的price则是传递给子组件的值

5、在对应的子组件中,通过props属性接收传递过来的值

props:{
        price:{
            type:String,
            default:''
        }
  }

6、在子组件中使用该值

单价:<span>{{price}}</span>

二、子组件向父组件传值

1 在Son.vue中,通过触发子组件的方法(这里是自定义的downPrice方法)

单价:<span>{{price}}</span> 
<button @click="downPrice">降价1元</button>

2 在子组件的methods的downPrice中,通过this.$emit(),将事件和参数传递给父组件

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

3 在父组件中接受子组件传递的事件downPrice和数据

<Son :price="price" @downPrice="downPrice"></Son>

4 父组件对接收到的事件和数据做出响应

downPrice(count) {
      this.price = (this.price - 1).toString();
    }

三、平级组件通信

同级组件不能直接传值,需要一个中间桥梁,可以先将数据传递给公共的父组件,然后父组件再将数据传递给需要的子组件。(一般大型的项目,推荐使用Vuex来管理组件之间的通信)

1 定义一个公共文件 eventBus.js,代码很简单,只是创建一个空的vue实例

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

2 在需要通信的同级组件中分别引入eventBus.js文件

import bus from '../eventBus.js'

3 在Son.vue中,通过$emit将事件和参数传递给Son.vue

price(newPrice){
          bus.$emit('priceChange',newPrice,this.count) 
} 

4 在Son.vue 中,通过$on接收接收参数和相应事件

bus.$on("priceChange", (price, count) => {
      this.balance = this.totalMoney - price * count;
    });

四、父组件调用子组件方法

1 在使用子组件时,给子组件加一个ref引用

<Son :price="price" @downPrice="downPrice" ref="page1"></Son>

2 父组件通过this.$refs即可找到该子组件,也可以操作子组件的方法

this.$refs.Son.子组件方法

或者可以通过$children,可以获取到所有子组件的集合

this.$children[0].某个方法

五、子组件调用父组件方法

1 通过 $parent可以找到父组件,进而调用其方法

this.$parent.父组件方法

猜你喜欢

转载自www.cnblogs.com/shemingxin/p/12504264.html