方法一:非父子组件之间的通信方式,可以通过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节点中,而并非是封装好的组件上
仅为学习记录,如有错误,请多包涵和指正,谢谢!