组件通信汇总

137 阅读1分钟

组件通信汇总

父子组件通信

1、传值

父传子

在父组件中通过v-bind绑定需要传递的参数

father.vue

<template>
  <div>
     <children :resolveValue="resolveValue"></children>
  </div>
</template>
<script>
import children from './children.vue'
export default {
  components: {
    children
  },
  data() {
    return {
      resolveValue: '父组件的值'
    }
  }

在子组件中定义props来接收从父组件传递过来的值

children.vue

<template>
  <div>
     子接父值:<span>{{ resolveValue }}</span>
  </div>
</template>
<script>
export default {
  props: ['resolveValue']
}

子传父

在子组件中通过this.$emit('父组件中方法名', 传参)来调用父组件中的方法,并将子组件的参数通过形参的方式传递到父组件

children.vue

// 调用father.vue中的getChildrenValue方法
this.$emit('getChildrenValue', '我是子组件的值')

father.vue

methods: {
    getChildrenValue(value) {
        console.log('获取到从子组件传来的值:', value)  // value == '我是子组件的值'
    }
}

2、触发方法

父组件调用子组件中的方法/属性

通过调用在子组件上添加ref属性来获取子组件的方法/属性

children.vue

<template>
  <div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      toParentValue: '从子组件传来的值'
    }
  },
  methods: {
    getMethods() {
      console.log('成功调用children.vue方法')
    },
  }
}

father.vue

<template>
  <div>
   <children :resolveValue="resolveValue" @getChildrenValue="getChildrenValue"></children>
  </div>
</template>
<script>
import children from './children.vue'
export default {
  components: {
    children
  },
  data() {
    return {
      resolveValue: '',
      inputValue: '',
      test: '父组件值',
      motherValue: '',
      publicValue: ''
    }
  },
  created() {},
  mounted() {
    // 监听mather.vue中的事件
    window.$channel.$on('mother-value', value => {
      this.motherValue = value
    })
    this.publicValue = this.$root.publicValue
  },
}
</script>

兄弟组件通信

1、传值

一共有三种方法:

1、设置eventBus事件中心

//设置事件中心的方法:1、在main.js中通过window.$channel = new Vue()
// 2、定义一个src/bus.js文件,并:import Vue from 'vue'; exprot default new Vue()
//   之后在兄弟组件中引入该文件。再通过bus.$on('监听名称', value => {})监听 bus.$emit('监听名称', 参数)触发 bus.$off 销毁

2、this.$root.属性

将公共属性定义在main.js中的new Vue()中的data中,可以直接通过this.$root.属性名来获取

3、this.$parent.属性

将公共属性定义在父组件中,可以通过this.$parent.属性获取

4、vuex

将属性定义在state中,可以公共修改

2、触发方法

通过this.$emit('父组件中方法')来触发父组件中的方法,并在该方法内通过在另一个兄弟组件上定义ref来获取该组件的方法/属性

跨组件通信

1、传值

provide/inject

在爷组件中通过provide添加依赖,只需要在后代组件中通过inject注入,即可获取到相关的方法/属性依赖。

2、触发方法