当前位置: 首页 > article >正文

vue3除了pinia/vuex的其他通讯方式还有那些

1. Props 和 Events
Props:父组件通过 props 向子组件传递数据。
Events:子组件通过 $emit 向父组件发送事件。

<!-- ParentComponent.vue -->
<template><ChildComponent :message="parentMessage" @update-message="updateMessage" />
</template><script setup lang="ts">
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';const parentMessage = ref('Hello from parent');function updateMessage(newMessage: string) {parentMessage.value = newMessage;
}
</script><!-- ChildComponent.vue -->
<template><div><p>{{ message }}</p><button @click="sendMessage">Send Message</button></div>
</template><script setup lang="ts">
const props = defineProps<{message: string;
}>();const emit = defineEmits<{(e: 'update-message', message: string): void;
}>();function sendMessage() {emit('update-message', 'Hello from child');
}
</script>

2. Provide / Inject
Provide:祖先组件通过 provide 提供数据。
Inject:后代组件通过 inject 获取数据。

<!-- AncestorComponent.vue -->
<template><DescendantComponent />
</template><script setup lang="ts">
import { provide, ref } from 'vue';
import DescendantComponent from './DescendantComponent.vue';const message = ref('Hello from ancestor');
provide('message', message);
</script><!-- DescendantComponent.vue -->
<template><div><p>{{ injectedMessage }}</p></div>
</template><script setup lang="ts">
import { inject } from 'vue';const injectedMessage = inject('message');
</script>

3. Event Bus
使用一个全局的 Vue 实例作为事件总线,组件可以通过它来发布和订阅事件。

// eventBus.ts
import { createApp } from 'vue';export const eventBus = createApp({});// ComponentA.vue
<script setup lang="ts">
import { eventBus } from './eventBus';function sendMessage() {eventBus.config.globalProperties.$emit('message', 'Hello from Component A');
}
</script>// ComponentB.vue
<script setup lang="ts">
import { onMounted } from 'vue';
import { eventBus } from './eventBus';onMounted(() => {eventBus.config.globalProperties.$on('message', (message: string) => {console.log(message);});
});
</script>

4. Reactive State
使用 Vue 的 reactive 或 ref 创建一个全局状态对象,组件之间共享这个状态。

// sharedState.ts
import { reactive } from 'vue';export const state = reactive({message: 'Hello from shared state',
});// ComponentA.vue
<script setup lang="ts">
import { state } from './sharedState';function updateMessage() {state.message = 'Updated message from Component A';
}
</script>// ComponentB.vue
<template><div><p>{{ state.message }}</p></div>
</template><script setup lang="ts">
import { state } from './sharedState';
</script>

5. Composables
使用 Vue 3 的 Composition API 创建可重用的逻辑,组件之间共享状态和逻辑。

// useSharedState.ts
import { ref } from 'vue';export function useSharedState() {const message = ref('Hello from composable');function updateMessage(newMessage: string) {message.value = newMessage;}return { message, updateMessage };
}// ComponentA.vue
<script setup lang="ts">
import { useSharedState } from './useSharedState';const { message, updateMessage } = useSharedState();function changeMessage() {updateMessage('Updated message from Component A');
}
</script>// ComponentB.vue
<template><div><p>{{ message }}</p></div>
</template><script setup lang="ts">
import { useSharedState } from './useSharedState';const { message } = useSharedState();
</script>

6. Teleport
使用 Teleport 将组件渲染到 DOM 中的其他位置,适用于模态框、通知等场景。

<!-- ParentComponent.vue -->
<template><div><button @click="showModal = true">Show Modal</button><Teleport to="body"><ModalComponent v-if="showModal" @close="showModal = false" /></Teleport></div>
</template><script setup lang="ts">
import { ref } from 'vue';
import ModalComponent from './ModalComponent.vue';const showModal = ref(false);
</script><!-- ModalComponent.vue -->
<template><div class="modal"><p>This is a modal</p><button @click="$emit('close')">Close</button></div>
</template><script setup lang="ts">
defineEmits(['close']);
</script>

7. Custom Directives
使用自定义指令在组件之间传递数据或执行操作。

// v-my-directive.ts
import { DirectiveBinding } from 'vue';export const myDirective = {mounted(el: HTMLElement, binding: DirectiveBinding) {el.addEventListener('click', () => {console.log('Directive triggered with value:', binding.value);});},
};// ComponentA.vue
<template><button v-my-directive="'Hello from directive'">Click me</button>
</template><script setup lang="ts">
import { myDirective } from './v-my-directive';
</script>

8. Global Properties
使用 app.config.globalProperties 添加全局属性或方法,所有组件都可以访问。

// main.ts
import { createApp } from 'vue';
import App from './App.vue';const app = createApp(App);app.config.globalProperties.$myGlobalFunction = () => {console.log('Hello from global function');
};app.mount('#app');// ComponentA.vue
<script setup lang="ts">
import { getCurrentInstance } from 'vue';const instance = getCurrentInstance();
instance?.proxy?.$myGlobalFunction();
</script>

9. Custom Events with mitt
使用第三方库 mitt 来实现轻量级的事件总线。

npm install mitt
// eventBus.ts
import mitt from 'mitt';export const eventBus = mitt();// ComponentA.vue
<script setup lang="ts">
import { eventBus } from './eventBus';function sendMessage() {eventBus.emit('message', 'Hello from Component A');
}
</script>// ComponentB.vue
<script setup lang="ts">
import { onMounted } from 'vue';
import { eventBus } from './eventBus';onMounted(() => {eventBus.on('message', (message: string) => {console.log(message);});
});
</script>

10. Context API
使用 Vue 3 的 provide 和 inject 来实现类似 React Context 的功能。

// context.ts
import { provide, inject, ref } from 'vue';const MessageSymbol = Symbol();export function provideMessage() {const message = ref('Hello from context');provide(MessageSymbol, message);
}export function useMessage() {const message = inject(MessageSymbol);if (!message) {throw new Error('Message not provided');}return message;
}// ParentComponent.vue
<script setup lang="ts">
import { provideMessage } from './context';
import ChildComponent from './ChildComponent.vue';provideMessage();
</script><template><ChildComponent />
</template>// ChildComponent.vue
<script setup lang="ts">
import { useMessage } from './context';const message = useMessage();
</script><template><div><p>{{ message }}</p></div>
</template>

相关文章:

vue3除了pinia/vuex的其他通讯方式还有那些

1. Props 和 Events Props&#xff1a;父组件通过 props 向子组件传递数据。 Events&#xff1a;子组件通过 $emit 向父组件发送事件。 <!-- ParentComponent.vue --> <template><ChildComponent :message"parentMessage" update-message"updat…...

【Python爬虫(80)】当Python爬虫邂逅边缘计算:探索数据采集新境界

【Python爬虫】专栏简介&#xff1a;本专栏是 Python 爬虫领域的集大成之作&#xff0c;共 100 章节。从 Python 基础语法、爬虫入门知识讲起&#xff0c;深入探讨反爬虫、多线程、分布式等进阶技术。以大量实例为支撑&#xff0c;覆盖网页、图片、音频等各类数据爬取&#xff…...

LLM之论文阅读——Context Size对RAG的影响

前言 RAG 系统已经在多个行业中得到广泛应用&#xff0c;尤其是在企业内部文档查询等场景中。尽管 RAG 系统的应用日益广泛&#xff0c;关于其最佳配置的研究却相对缺乏&#xff0c;特别是在上下文大小、基础 LLM 选择以及检索方法等方面。 论文原文: On the Influence of Co…...

2025-02-25 学习记录--C/C++-用C语言实现删除字符串中的子串

用C语言实现删除字符串中的子串 在C语言中&#xff0c;你可以使用strstr函数来查找子串&#xff0c;然后用memmove或strcpy来覆盖或删除找到的子串。 一、举例 &#x1f430; #include <stdio.h> // 包含标准输入输出库&#xff0c;用于使用 printf 函数 #include <s…...

网络原理--常见的请求和响应的格式

1.xml 类似于html&#xff0c;也是一种标签语言&#xff0c;标签成对出现。 例如&#xff1a; <request> <userId>1000</userId> </request> 其中&#xff1a; <userId>称为开始标签&#xff0c;</userId>称为结束标签。开始标签和结…...

【Linux】Ubuntu服务器的安装和配置管理

ℹ️大家好&#xff0c;我是练小杰&#xff0c;今天周二了&#xff0c;哪吒的票房已经到了138亿了&#xff0c;饺子导演好样的&#xff01;&#xff01;每个人的成功都不是必然的&#xff0c;坚信自己现在做的事是可以的&#xff01;&#xff01;&#x1f606; 本文是有关Ubunt…...

2.3做logstash实验

收集apache日志输出到es 在真实服务器安装logstash&#xff0c;httpd systemctl start httpd echo 666 > /var/www/html/index.html cat /usr/local/logstash/vendor/bundle/jruby/2.3.0/gems/logstash-patterns-core-4.1.2/patterns/httpd #系统内置变量 cd /usr/local/…...

pandas读取数据

pandas读取数据 导入需要的包 import pandas as pd import numpy as np import warnings import oswarnings.filterwarnings(ignore)读取纯文本文件 pd.read_csv 使用默认的标题行、逗号分隔符 import pandas as pd fpath "./datas/ml-latest-small/ratings.csv" 使…...

rabbitmq 延时队列

要使用 RabbitMQ Delayed Message Plugin 实现延时队列&#xff0c;首先需要确保插件已安装并启用。以下是实现延时队列的步骤和代码示例。 1. 安装 RabbitMQ Delayed Message Plugin 首先&#xff0c;确保你的 RabbitMQ 安装了 rabbitmq-delayed-message-exchange 插件。你可…...

Deepseek 实战全攻略,领航科技应用的深度探索之旅

想玩转 Deepseek&#xff1f;这攻略别错过&#xff01;先带你了解它的基本原理&#xff0c;教你搭建运行环境。接着给出自然语言处理、智能客服等应用场景的实操方法与代码。还分享模型微调、优化技巧&#xff0c;结合案例加深理解&#xff0c;让你全面掌握&#xff0c;探索科技…...

Go语言中的信号量:原理与实践指南

Go语言中的信号量&#xff1a;原理与实践指南 引言 在并发编程中&#xff0c;控制对共享资源的访问是一个经典问题。Go语言提供了丰富的并发原语&#xff08;如sync.Mutex&#xff09;&#xff0c;但当我们需要灵活限制并发数量时&#xff0c;信号量&#xff08;Semaphore&am…...

计算机网络与通讯知识总结

计算机网络与通讯知识总结 基础知识总结 1)FTP:文件传输 SSH:远程登录 HTTP:网址访问 2)‌交换机 定义‌:一种基于MAC地址实现局域网(LAN)内数据高速转发的网络设备,可为接入设备提供独享通信通道‌。 -‌ 核心功能‌: 1.数据链路层(OSI第二层)工作,通过MAC地址…...

ReentrantLock 用法与源码剖析笔记

&#x1f4d2; ReentrantLock 用法与源码剖析笔记 &#x1f680; 一、ReentrantLock 核心特性 &#x1f504; 可重入性&#xff1a;同一线程可重复获取锁&#xff08;最大递归次数为 Integer.MAX_VALUE&#xff09;&#x1f527; 公平性&#xff1a;支持公平锁&#xff08;按等…...

Vscode无法加载文件,因为在此系统上禁止运行脚本

1.在 vscode 终端执行 get-ExecutionPolicy 如果返回是Restricted&#xff0c;说明是禁止状态。 2.在 vscode 终端执行set-ExecutionPolicy RemoteSigned 爆红说明没有设置成功 3.在 vscode 终端执行Set-ExecutionPolicy -Scope CurrentUser RemoteSigned 然后成功后你再在终…...

java进阶专栏的学习指南

学习指南 java类和对象java内部类和常用类javaIO流 java类和对象 类和对象 java内部类和常用类 java内部类精讲Object类包装类的认识String类、BigDecimal类初探Date类、Calendar类、SimpleDateFormat类的认识java Random类、File类、System类初识 javaIO流 java IO流【…...

架构思维:架构的演进之路

文章目录 引言为什么架构思维如此重要架构师的特点软件架构的知识体系如何提升架构思维大型互联网系统架构的演进之路一、大型互联网系统的特点二、系统处理能力提升的两种途径三、大型互联网系统架构演化过程四、总结 引言 在软件开发行业中&#xff0c;有很多技术人可能会问…...

VC++零基础入门之系列教程 【附录E MFC快速参考指南】

附录E MFC快速参考指南 E.1 创建窗口 使用M F C CWnd wnd; W n d . C r e a t e E x ( E xSt y l e , C l a s s N a m e , Wi n d o w N a m e , S t y l e , x , y, Wi d t h , H e i g h t , P a r e n t , M e n u , P a r a m ) ; 使用A P I HWND hwnd=::CreateWi n d …...

vue3:vue3项目安装并引入Element-plus

一、安装Element-plus 1、安装语句位置 安装 | Element Plushttps://element-plus.org/zh-CN/guide/installation.html根据所需进行安装&#xff0c;这里使用npm包 2、找到项目位置 找到项目位置&#xff0c;在路径上输入cmd回车打开“运行”窗口 输入安装语句回车完成安装 …...

一文掌握python中正则表达式的各种使用

文章目录 1. 正则表达式基础1.1 常用元字符1.2 基本用法 2. 正则表达式高级功能2.1 分组捕获2.2 命名分组2.3 非贪婪匹配2.4 零宽断言2.5 编译正则表达式2.6 转义字符 3. 常见应用场景3.1 验证邮箱格式3.2 提取 URL3.3 提取日期3.4 提取HTML中的链接3.5 提取HTML中的图片链接3.…...

java.2.25

1. 注释 ​ 注释是对代码的解释和说明文字。 Java中的注释分为三种&#xff1a; 单行注释&#xff1a; // 这是单行注释文字多行注释&#xff1a; /* 这是多行注释文字 这是多行注释文字 这是多行注释文字 */ 注意&#xff1a;多行注释不能嵌套使用。文档注释&#xff1a;…...

45.matlab产生正弦叠加信号

&#xff0c;...

VScode 开发

目录 安装 VS Code 创建一个 Python 代码文件 安装 VS Code VSCode&#xff08;全称&#xff1a;Visual Studio Code&#xff09;是一款由微软开发且跨平台的免费源代码编辑器&#xff0c;VSCode 开发环境非常简单易用。 VSCode 安装也很简单&#xff0c;打开官网 Visual S…...

在llm和agent的背景下,有什么比较好的研究方向或者能解决现在的实际的社会问题

在llm和agent的背景下,有什么比较好的研究方向或者能解决现在的实际的社会问题 在LLM(大语言模型)与Agent(智能体)的融合背景下,研究方向和社会应用正呈现出多元化趋势。 一、技术研究方向 多模态智能体(Multi-modal Agents) 方向:将LLM与视觉、语音、触觉等多模态数…...

A Large Recurrent Action Model: xLSTM Enables Fast Inference for Robotics Tasks

奥地利林茨约翰开普勒大学机器学习研究所 ELLIS 小组&#xff0c;LIT 人工智能实验室奥地利林茨 NXAI 有限公司谷歌 DeepMind米拉 - 魁北克人工智能研究所 摘要 近年来&#xff0c;强化学习&#xff08;Reinforcement Learning, RL&#xff09;领域出现了一种趋势&#xff0c;…...

CSS按钮点击效果实战:scale(0.95) 与10个交互动画优化指南

[TOC](CSS按钮点击效果实战&#xff1a;scale(0.95) 与10个交互动画优化指南) 导语 在现代 Web 开发中&#xff0c;细腻的交互效果是提升用户体验的关键。通过简单的 CSS 动画&#xff08;如 transform: scale(0.95)&#xff09;&#xff0c;无需 JavaScript 即可实现高效、流…...

计算机毕业设计SpringBoot+Vue.js学科竞赛管理系统(源码+文档+PPT+讲解)

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…...

在Spring Boot+Vue前后端分离的项目中使用JWT实现基本的权限校验

说明 在 Spring Boot + Vue 前后端分离的项目中,如果不使用第三方服务(如 Spring Security、Shiro 等),可以通过自定义实现基本的权限校验。 使用JWT实现步骤 以下是实现步骤: 1. 设计权限模型 通常权限模型包括: 用户(User):系统的使用者。角色(Role):用户的权…...

Deep Seek-编码器

1. DeepSeek Coder 简介 DeepSeek Coder 由一系列代码语言模型组成,每个模型都在 2T 令牌上从头开始训练,其中 87% 的代码和 13% 的自然语言在中英文中组成。我们提供各种大小的代码模型,从 1B 到 33B 版本。每个模型都通过采用 16K 的窗口大小和额外的填空任务在项目级代码…...

在 MySQL 的 InnoDB 存储引擎中,部分数据库优化策略

在 MySQL 的 InnoDB 存储引擎中&#xff0c;以下操作是 同步的&#xff0c;并且会直接影响数据库执行 SQL 的效率&#xff1a; 1. Redo Log 的同步刷盘&#xff08;事务提交时&#xff09; 触发条件&#xff1a; 当 innodb_flush_log_at_trx_commit1 时&#xff0c;事务提交时强…...

一文掌握DrissionPage的详细使用

文章目录 1. 什么是DrissionPage&#xff1f;2. 安装 DrissionPage3. 基本使用3.1 初始化浏览器3.2 打开网页3.3 查找元素3.4 操作元素3.5 获取元素属性3.6 执行 JavaScript3.7 页面对象&#xff08;Page Object&#xff09;3.8 元素定位方式3.9 常用操作方法3.10 断言 4. 高级…...