当前位置:首页 > 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>

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

相关文章

react如何完成组件通信

react如何完成组件通信

父子组件通信 父组件通过props向子组件传递数据。子组件通过调用父组件传递的回调函数与父组件通信。 // 父组件 function Parent() { const [data, setDat…

如何创建一个react实例

如何创建一个react实例

安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可以通过命令行验证安装: node -v npm -v 若未安装,需从 Node.js 官网 下载并安装。 使…

php实现udp通信

php实现udp通信

PHP实现UDP通信 UDP(用户数据报协议)是一种无连接的传输层协议,适用于对实时性要求高但允许少量丢包的场景。PHP可以通过socket扩展实现UDP通信。 创建UDP服务器 $socket =…

php 实现通信

php 实现通信

PHP 实现通信的方法 PHP 可以通过多种方式实现通信,包括 HTTP 请求、Socket 编程、消息队列等。以下是几种常见的实现方式: HTTP 请求(cURL 或 file_get_conte…

js实现通信

js实现通信

JavaScript 实现通信的方法 JavaScript 提供了多种方式实现不同场景下的通信,包括浏览器与服务器、页面间、跨域等场景。 原生 AJAX 通信 使用 XMLHttpRequest 对…

java如何实例化

java如何实例化

实例化对象的基本语法 在Java中,实例化对象需要使用new关键字,后跟类的构造函数。基本语法如下: ClassName objectName = new ClassName(); 通过构造函数实例…