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

news2025/2/26 15:29:40

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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2306435.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

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…

【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" 使…

ReentrantLock 用法与源码剖析笔记

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

java进阶专栏的学习指南

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

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

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

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

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

java.2.25

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

VScode 开发

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

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

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

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

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

Deep Seek-编码器

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

Android平台轻量级RTSP服务模块技术对接说明

一、技术背景 随着内网无纸化办公、电子教室等应用场景对超低延迟音视频传输需求的日益增长&#xff0c;为避免用户或开发者单独部署 RTSP 或 RTMP 服务&#xff0c;大牛直播 SDK 推出了轻量级 RTSP 服务 SDK。该 SDK 能够将本地音视频数据&#xff08;如摄像头、麦克风等&…

RoCEv2 高性能传输协议与 Lossless 无损网络

目录 文章目录 目录RoCERoCEv2 v.s. IBRoCEv2 协议栈RoCEv2 需要 Lossless NetworkLossless Network 拥塞控制技术网络拥塞的原因PFC 基于优先级的流量控制PFC Unfairness &#xff08;带宽分配不公平&#xff09;的问题PFC HOL&#xff08;队头拥塞&#xff09;的问题PFC Dead…

联想 SR590 服务器 530-8i RAID 控制器更换损坏的硬盘

坏了的硬盘会自动亮黄灯。用一个空的新盘来替换&#xff0c;新盘最好不要有东西。但是有东西可能也没啥&#xff0c;因为我看 RAID 控制器里有格式化的选项 1. 从 IPMI 把服务器关机&#xff0c;电源键进入绿色闪烁状态 2. 断电&#xff0c;推开塑料滑块拉出支架&#xff0c;…

城电科技|会追日的智能花,光伏太阳花开启绿色能源新篇章

当艺术与科技相遇&#xff0c;会碰撞出怎样的火花&#xff1f;城电科技推出的光伏太阳花&#xff0c;以其独特的设计与智能化的功能&#xff0c;给出了答案。这款产品不仅具备太阳能发电的实用功能&#xff0c;更是一件充满科技属性的艺术性光伏产品&#xff0c;吸引了广泛关注…

基于YOLO11深度学习的苹果叶片病害检测识别系统【python源码+Pyqt5界面+数据集+训练代码】

《------往期经典推荐------》 一、AI应用软件开发实战专栏【链接】 项目名称项目名称1.【人脸识别与管理系统开发】2.【车牌识别与自动收费管理系统开发】3.【手势识别系统开发】4.【人脸面部活体检测系统开发】5.【图片风格快速迁移软件开发】6.【人脸表表情识别系统】7.【…