当前位置:首页 > VUE

使用vue实例实现通信

2026-01-20 17:41:15VUE

Vue 实例通信方法

父子组件通信

使用 props 传递数据给子组件,子组件通过 $emit 触发事件传递数据给父组件。

父组件:

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

<script>
export default {
  data() {
    return {
      parentMessage: 'Hello from parent'
    }
  },
  methods: {
    handleUpdate(newMessage) {
      this.parentMessage = newMessage
    }
  }
}
</script>

子组件:

<template>
  <button @click="sendMessage">Send Message</button>
</template>

<script>
export default {
  props: ['message'],
  methods: {
    sendMessage() {
      this.$emit('update', 'New message from child')
    }
  }
}
</script>

兄弟组件通信

通过共享的父组件作为中介,或者使用事件总线。

事件总线方法:

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

组件A:

import { EventBus } from './event-bus.js'
EventBus.$emit('message', 'Hello from A')

组件B:

使用vue实例实现通信

import { EventBus } from './event-bus.js'
EventBus.$on('message', (msg) => {
  console.log(msg)
})

跨层级组件通信

使用 provide/inject 实现祖先组件向后代组件传递数据。

祖先组件:

export default {
  provide() {
    return {
      sharedData: this.sharedData
    }
  },
  data() {
    return {
      sharedData: 'Shared information'
    }
  }
}

后代组件:

export default {
  inject: ['sharedData'],
  created() {
    console.log(this.sharedData)
  }
}

Vuex 状态管理

使用vue实例实现通信

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

store.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})

组件中使用:

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

$refs 直接访问

通过 ref 属性直接访问组件实例或DOM元素。

<template>
  <ChildComponent ref="child" />
  <button @click="callChildMethod">Call Child Method</button>
</template>

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

标签: 实例通信
分享给朋友:

相关文章

elementui实例

elementui实例

以下是关于 Element UI 实例的整理内容,涵盖常见组件用法和实际开发中的关键点: 安装与基础配置 通过 npm 安装 Element UI: npm install element-ui…

vue实现导出 实例

vue实现导出 实例

Vue实现导出功能的方法 在Vue中实现导出功能通常涉及将数据导出为Excel、CSV或其他格式文件。以下是几种常见的实现方式: 使用xlsx库导出Excel 安装xlsx库: npm insta…

vue实现串口通信

vue实现串口通信

vue实现串口通信的方法 Vue本身不直接支持串口通信,但可以通过浏览器API或第三方库实现。以下是几种常见方法: 使用Web Serial API Web Serial API是现代浏览器提供的原…

vue实现html页面实例

vue实现html页面实例

Vue 实现 HTML 页面实例 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是一个简单的 Vue 实现 HTML 页面的实例,展示如何将 Vue 集成到 HTML…

react模型之间如何通信

react模型之间如何通信

组件间通信方法 父组件向子组件传递数据 通过props传递数据,子组件通过this.props(类组件)或直接解构props(函数组件)接收。 示例: // 父组件 <ChildCompo…

react组件之间是如何通信

react组件之间是如何通信

父子组件通信(Props) 父组件通过props向子组件传递数据或方法,子组件通过接收props实现数据或行为的更新。父组件定义props,子组件通过this.props(类组件)或直接解构(函数组件…