当前位置:首页 > VUE

vue实现父子组件

2026-03-29 08:25:03VUE

Vue 父子组件通信实现方法

父组件向子组件传递数据(Props)

在父组件中通过v-bind或简写:向子组件传递数据。子组件通过props接收数据。

父组件模板:

<template>
  <child-component :message="parentMessage" />
</template>

子组件接收:

export default {
  props: {
    message: {
      type: String,
      required: true
    }
  }
}

子组件向父组件传递数据(自定义事件)

子组件通过$emit触发自定义事件,父组件通过v-on或简写@监听事件。

子组件触发:

this.$emit('update', newValue)

父组件监听:

<template>
  <child-component @update="handleUpdate" />
</template>

使用v-model实现双向绑定

子组件需要声明model选项并处理value属性和input事件。

子组件实现:

export default {
  model: {
    prop: 'value',
    event: 'input'
  },
  props: ['value'],
  methods: {
    updateValue(newVal) {
      this.$emit('input', newVal)
    }
  }
}

父组件使用:

<child-component v-model="parentData" />

使用$refs访问子组件

父组件可以通过ref属性直接访问子组件实例和方法。

vue实现父子组件

父组件设置ref:

<child-component ref="childRef" />

父组件调用方法:

this.$refs.childRef.childMethod()

使用provide/inject跨层级通信

适用于深层嵌套组件,祖先组件提供数据,后代组件注入使用。

祖先组件:

export default {
  provide() {
    return {
      sharedData: this.sharedData
    }
  }
}

后代组件:

export default {
  inject: ['sharedData']
}

使用事件总线(Event Bus)

创建单独的Vue实例作为中央事件总线,实现任意组件间通信。

vue实现父子组件

创建事件总线:

export const eventBus = new Vue()

发送事件:

eventBus.$emit('event-name', data)

接收事件:

eventBus.$on('event-name', data => {
  // 处理数据
})

使用Vuex状态管理

对于复杂应用,使用Vuex集中管理组件共享状态。

store定义:

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

组件中使用:

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

标签: 父子组件
分享给朋友:

相关文章

vue轮播组件实现

vue轮播组件实现

vue轮播组件实现方法 使用第三方库(如Swiper) 安装Swiper库: npm install swiper 在Vue组件中引入: <template> <div cl…

vue实现广告组件

vue实现广告组件

vue实现广告组件的方法 使用动态组件实现 在Vue中可以通过动态组件的方式加载广告组件,根据不同的条件展示不同的广告内容。动态组件使用<component :is="currentCompon…

vue实现折叠组件

vue实现折叠组件

实现折叠组件的基本思路 在Vue中实现折叠组件通常需要利用动态绑定和条件渲染。核心是通过控制一个布尔值状态来决定内容是否显示,并添加过渡动画提升用户体验。 基础实现方法 使用v-show或v-if控…

react组件如何通讯

react组件如何通讯

React 组件通讯方式 React 组件间的通讯方式主要包括以下几种方法,适用于不同场景下的数据传递和状态管理需求。 父子组件通讯(Props 传递) 父组件通过 props 向子组件传递数据或回…

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性来完成。以下是几种常见的实…

react如何删除组件

react如何删除组件

删除 React 组件的几种方法 条件渲染法 通过状态控制组件是否渲染。当状态为 false 时,组件会被移除: const [showComponent, setShowComponent…