非父子组件通信

方法一:非父子组件之间的通信方式,可以通过eventBus,在一个组建中创建时的钩子函数中监听某个事件,在需要与其进行通信的组件中触发这个函数,同时进行数据的交换

  • eventBus.js
import Vue from 'vue'
export default new Vue  
  • parentTemplate.vue
<template>
  <h3 @click="opera">Hello Vue</h3>
</template>

<script>
 import bus from './eventBus'
 export default {
   name: 'parentTemplate',
   methods: {
     opera () {
       // 触发函数
       bus.$emit('smOpera')
     }
   }
 }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
  • childTemplate.vue
<template>
   <div></div>
</template>

<script>
 import bus from './eventBus'
 export default {
   name: 'childTemplate',
   mounted () {
     // 监听事件
     bus.$on('clearData', function () {
        // do something
     })
   }
 }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

方法二:非父子组件通信还可以使用ref,ref是一个对象,持有注册过ref特性的所有DOM元素和组件实例

  • 父组件可以通过ref调用子组件中的方法属性

  • refParentTemplate.vue

<template>
  <div>
    <!--动态组件-->
    <component v-bind:is="currentView" ref="componentRel" @changeStep="changeStep"></component>
  </div>
</template>
<script>
  import refChildTemplatefrom './refChildTemplate'
  export default {
    name: 'parentTemplate',
    data () {
      return {
        currentView: 'step0'
      }
    },
    components: {
      step0: childTemplate
    },
    methods: {
      changeStep () {
        // 调用子组件的方法
        this.$refs['componentRel'].clearFormData()
      }
    }
  }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
  • refChildTemplate.vue
<template>
  <div>
    <span>{{ msg }}</span>
  </div>
</template>
<script>
  export default {
    name: 'refChildTemplate',
    data () {
      return {
        msg: '子组件页面'
      }
    },
    methods: {
      clearFormData () {
       this.msg = '父组件调用'
      }
    }
  }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

额外补充一点

  • vue.$refs['refName'].$el 可以获取DOM元素 ,前提条件下ref必须在组件中声明

  • vue.$refs['refName]同样可以获取DOM元素,这里ref的声明是在DOM节点中,而并非是封装好的组件上

仅为学习记录,如有错误,请多包涵和指正,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值