vue组件通信

本文详细讲解了Vue中props与$emit的父子组件数据传递,eventBus事件总线的应用,依赖注入的深度通信,以及ref/$refs的组件交互。重点介绍了如何利用这些技术实现跨组件间的高效通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1) props / $emit

父组件通过props向子组件传递数据,子组件通过$emit和父组件通信

1. 父--->子

  • props只能是父组件向子组件进行传值,props使得父子组件之间形成了一个单向下行绑定。子组件的数据会随着父组件不断更新。
  • props 可以显示定义一个或一个以上的数据,对于接收的数据,可以是各种数据类型,同样也可以传递一个函数。
  • props属性名规则:若在props中使用驼峰形式,模板中需要使用短横线的形式

2,子--->

$emit绑定一个自定义事件,当这个事件被执行的时就会将参数传递给父组件,而父组件通过v-on监听并接收参数。

父组件给子组件绑定事件(v-on:test=fn),并定义回调函数,子组件通过this.$emit(test)触发父组件中的回调函数

(2)eventBus事件总线(emit/on)

eventBus事件总线适用于父子组件非父子组件等之间的通信,

1,安装全局事件总线

 2,接收方:往总线上绑定事件,并定义回调函数

 3,发送方:往总线上触发事件,并传递参数

 

最好在beforeDestroy钩子中解绑当前组件所用到的事件

(3)依赖注入(project / inject)

用于父子组件之间的通信。当然这里所说的父子不一定是真正的父子,也可以是祖孙组件,在层数很深的情况下,可以使用这种方法来进行传值。就不用一层一层的传递了。

注意: 依赖注入所提供的属性是非响应式

project / inject是Vue提供的两个钩子,和data、methods是同级的。并且project的书写形式和data一样。

  • project 钩子用来发送数据或方法
  • inject钩子用来接收数据或方法

4)ref / $refs

这种方式也是实现父子组件之间的通信。

ref: 这个属性用在子组件上,它的引用就指向了子组件的实例。可以通过实例来访问组件的数据和方法。

父组件:在子组件的实例化标签中打标识ref=’xxx’,就可以通过this.$refs.xxx操作子组件上的数据和方法

 子组件不需要做任何操作:

 5parent/children

  • 使用$parent可以让组件访问父组件的实例(访问的是上一级父组件的属性和方法
  • 使用$children可以让组件访问子组件的实例,但是,$children并不能保证顺序,并且访问的数据也不是响应式的。

子组件中使用$parent访问父组件的数据和方法:

 父组件中使用$children访问子组件的数据(非响应式)和方法:

需要注意:

  • 通过$parent访问到的是上一级父组件的实例,可以使用$root来访问根组件的实例
  • 在组件中使用$children拿到的是所有的子组件的实例,它是一个数组,并且是无序的
  • 根组件#app上拿$parent得到的是new Vue()的实例,在这实例上再拿$parent得到的是undefined,而在最底层的子组件拿$children是个空数组
  • $children 的值是数组,而$parent是个对象 

5attrs/listeners

Vue引入了$attrs / $listeners,实现组件之间的跨代通信。

inheritAttrs

父组件传递的props参数,如果子组件没有声明接收(props:[]):

如果inheritAttrs为true,则这些没有声明的属性变为子组件根元素上的html属性

如果inheritAttrs为false,则没有声明的props属性不会变为html的属性

$attrs

$attrs保存了绑定在组件上不被识别为props的所有属性(没有声明接收的props(class 和 style 除外)

不论inheritAttrs是true还是false,子组件的$attrs都能接收到未声明的props

通过v-bind=‘$attrs’,可以把本组件的$attrs传递给子组件

$listeners

它是一个对象,里面包含了作用在这个组件上所有的监听器(监听事件),可以通过 v-on="$listeners" 将事件监听指向这个组件内的子元素(包括内部的子组件)

把父组件的事件传递给子组件,子组件可以触发父组件中的回调

总结:

父组件:props传参,传递自定义事件(test),定义回调函数fn

<template>

<child  name:’hhh’ age:’18’@test=”fn”><child/>

<template/>

子组件:没有声明接收的props参数在$attrs中,把$attrs传递给孙组件, (name,age)

并通过 v-on=$listeners 把子组件的事件监听器给孙组件,孙组件 可以触发test事件

<template>

<sun v-bind="$attrs" v-on="$listeners"><sun/>

<template>

孙组件可以直接使用数据(name,age),也可以触发事件 this.$emit(test)

### Vue 组件间的通信方法 Vue 提供了多种组件通信的方式,适用于不同的场景和需求。以下是常见的 Vue 组件通信方法及其实现技巧: #### 1. **Props 和 $emit** `props` 是父组件向子组件传递数据的主要方式,而 `$emit` 则用于子组件向父组件发送事件通知。 - 父组件通过 `props` 将数据传递到子组件中[^1]。 - 子组件可以通过调用 `$emit` 方法触发自定义事件,并将数据回传给父组件[^2]。 示例代码如下: ```vue <!-- ParentComponent.vue --> <template> <ChildComponent :message="parentMessage" @childEvent="handleChildEvent" /> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentMessage: 'Hello from Parent', }; }, methods: { handleChildEvent(data) { console.log('Data received from child:', data); } } }; </script> ``` ```vue <!-- ChildComponent.vue --> <template> <div>{{ message }}</div> </template> <script> export default { props: ['message'], mounted() { this.$emit('childEvent', 'Hello from Child'); } }; </script> ``` --- #### 2. **Provide 和 Inject** `provide/inject` 主要用于跨多层嵌套的父子组件之间共享状态,适合全局配置或深层嵌套的情况。 示例代码如下: ```javascript // ParentComponent.vue export default { provide() { return { sharedState: this.sharedState, }; }, data() { return { sharedState: 'Shared Data', }; }, }; // DeeplyNestedChildComponent.vue export default { inject: ['sharedState'], created() { console.log(this.sharedState); // 输出 "Shared Data" }, }; ``` --- #### 3. **v-model (双向绑定)** `v-model` 实现了父子组件之间的双向绑定,通常用于表单输入控件。 示例代码如下: ```vue <!-- ParentComponent.vue --> <template> <CustomInput v-model="inputValue" /> </template> <script> import CustomInput from './CustomInput.vue'; export default { components: { CustomInput }, data() { return { inputValue: '', }; }, }; </script> ``` ```vue <!-- CustomInput.vue --> <template> <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" /> </template> <script> export default { props: ['modelValue'], }; </script> ``` --- #### 4. **Vuex (集中式状态管理)** 对于复杂的大型项目,推荐使用 Vuex 来统一管理和分发状态。 示例代码如下: ```javascript // store.js import { createStore } from 'vuex'; const store = createStore({ state: { count: 0, }, mutations: { increment(state) { state.count++; }, }, }); export default store; ``` ```vue <!-- AnyComponent.vue --> <template> <button @click="increment">Increment Count</button> {{ count }} </template> <script> export default { computed: { count() { return this.$store.state.count; }, }, methods: { increment() { this.$store.commit('increment'); }, }, }; </script> ``` --- #### 5. **Mitt 或 Event Bus** 如果不想引入 Vuex,可以使用轻量级库 Mitt 创建一个简单的事件总线来处理非父子关系的组件通信。 示例代码如下: ```javascript // eventBus.js import mitt from 'mitt'; const emitter = mitt(); export default emitter; // ComponentA.vue emitter.emit('custom-event', payload); // ComponentB.vue emitter.on('custom-event', handlerFunction); ``` --- #### 6. **Expose/Ref** 在组合式 API 中,`ref` 可以用来访问子组件实例中的公开属性或方法,配合 `defineExpose` 使用。 示例代码如下: ```vue <!-- ParentComponent.vue --> <template> <ChildComponent ref="childRef" /> </template> <script setup> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; const childRef = ref(null); function callChildMethod() { childRef.value?.publicMethod(); } </script> ``` ```vue <!-- ChildComponent.vue --> <script setup> defineExpose({ publicMethod() {}, }); </script> ``` --- #### 7. **Attrs 和 Listeners** 当某些属性未被声明为 `props` 时,它们会自动成为 `attrs` 并向下传播;类似的还有 `$listeners`,不过在 Vue 3 中已被移除并替换为 `v-on`。 示例代码如下: ```vue <!-- GrandParentComponent.vue --> <template> <ParentComponent customAttr="test" @customEvent="handleCustomEvent" /> </template> ``` ```vue <!-- ParentComponent.vue --> <template> <ChildComponent v-bind="$attrs" v-on="$listeners" /> </template> <script> export default { inheritAttrs: false, // 防止 attrs 被挂载到根节点上 }; </script> ``` --- #### 总结 以上列举了几种主流的 Vue 组件通信方式,每种都有其适用范围和特点。开发者应根据具体业务需求选择合适的方案。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值