当前位置:首页 > VUE

vue实现通讯

2026-03-07 10:31:16VUE

Vue 组件间通讯方法

Props 和 Events 父组件通过 props 向子组件传递数据,子组件通过 $emit 触发事件向父组件传递数据。这是 Vue 中最基础的父子组件通讯方式。

父组件模板:

<template>
  <ChildComponent :message="parentMessage" @update="handleUpdate"/>
</template>

子组件模板:

<template>
  <button @click="$emit('update', newValue)">Update</button>
</template>

<script>
export default {
  props: ['message']
}
</script>

Provide/Inject 适合跨多级组件传递数据,祖先组件通过 provide 提供数据,后代组件通过 inject 注入数据。这种方式避免了逐层传递 props 的繁琐。

祖先组件:

export default {
  provide() {
    return {
      theme: this.themeData
    }
  }
}

后代组件:

export default {
  inject: ['theme']
}

Event Bus 创建一个中央事件总线,用于任意组件间的通讯。通常新建一个 Vue 实例作为事件中心。

创建 event bus:

// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()

组件中使用:

// 发送事件
EventBus.$emit('eventName', data)

// 接收事件
EventBus.$on('eventName', data => {
  // 处理数据
})

Vuex 状态管理 对于大型应用,Vuex 提供了集中式状态管理。所有组件都可以访问和修改 store 中的状态。

store 定义:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})

组件中使用:

this.$store.commit('increment')
console.log(this.$store.state.count)

$refs 父组件可以通过 ref 直接访问子组件实例和方法。这种方式打破了组件封装性,应谨慎使用。

父组件模板:

<template>
  <ChildComponent ref="child"/>
</template>

<script>
export default {
  mounted() {
    this.$refs.child.childMethod()
  }
}
</script>

$parent 和 $children 通过组件实例的 $parent 和 $children 属性访问父子组件实例。这种方式同样会破坏组件封装,不推荐频繁使用。

// 访问父组件
this.$parent.parentMethod()

// 访问子组件
this.$children[0].childMethod()

v-model 语法糖 v-model 实际上是 props 和 events 的语法糖,适合表单控件等双向数据绑定场景。

自定义组件支持 v-model:

export default {
  model: {
    prop: 'value',
    event: 'input'
  },
  props: ['value']
}

作用域插槽 通过作用域插槽可以让父组件访问子组件内部数据,实现更灵活的组件组合。

子组件模板:

<template>
  <slot :user="user"></slot>
</template>

父组件使用:

vue实现通讯

<template>
  <ChildComponent>
    <template v-slot:default="slotProps">
      {{ slotProps.user.name }}
    </template>
  </ChildComponent>
</template>

选择通讯方式时应考虑组件关系和数据流复杂度。简单父子通讯用 props/events,跨层级用 provide/inject,复杂应用状态管理用 Vuex,全局事件用 Event Bus。

标签: 通讯vue
分享给朋友:

相关文章

vue实现管道

vue实现管道

Vue 中实现管道(Pipe)功能 在 Vue 中可以通过过滤器(Filters)或计算属性(Computed Properties)实现类似管道的功能,将数据经过多个处理步骤后输出。 使用过滤器(…

vue实现input

vue实现input

Vue 实现 Input 输入框的方法 基本双向绑定 使用 v-model 指令实现双向数据绑定,适用于大多数表单场景: <template> <input v-model="…

vue实现表白

vue实现表白

Vue 实现表白页面 使用 Vue 可以快速创建一个动态、交互式的表白页面。以下是一个简单的实现方案: 基础结构 创建一个 Vue 项目或单文件组件,包含以下核心部分: <template&…

vue系统实现

vue系统实现

Vue 系统实现的关键步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目,安装核心依赖(如 Vue 3、Vue Router、Pinia)。配置开发环境(如 ESLint、Prett…

vue实现导航栏

vue实现导航栏

使用 Vue 实现导航栏 基础导航栏结构 在 Vue 中实现导航栏通常使用 <router-link> 或自定义组件。以下是一个基础示例: <template> <…

vue实现tab功能

vue实现tab功能

Vue 实现 Tab 功能的方法 使用动态组件和 v-if 指令 通过 v-if 或 v-show 控制不同 Tab 内容的显示与隐藏。这种方法适合简单的 Tab 切换需求。 <tem…