工作中使用组件之间传值在此记录

目录
VUE3中的组件通信六种方法介绍与基本使用
一、父传子(props)
二、 Emits 传值(子组件向父组件传值)
三、v-model 双向绑定
四、 provide/inject(跨层级组件传值)
五、事件总线(mitt 库)第三方库
六、 Vuex 或 Pinia(状态管理库)
VUE3中的组件通信六种方法介绍与基本使用
一、父传子(props)
Props 是最常用的父组件向子组件传递数据的方式。父组件通过属性绑定将数据传递给子组件,子组件使用 defineProps 来接收数据。

父组件

<template>
<ChildComponent :list="list" />
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const list= ref([
{name:“我是测试数据”}
]);
</script>
子组件

```bash
<template>
<p>{{ list[0].name}}</p>
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
list: {
type: Arrary,
default: []
}
});
</script>```
二、 Emits 传值(子组件向父组件传值)
子组件可以通过 defineEmits 定义自定义事件,使用 emit 触发事件并传递数据给父组件。多用于表单提交等

父组件

<template>
<ChildComponent @customEvent="handleChildEvent" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';

const handleChildEvent = (data) => {
console.log('Received data from child:', data);
};
</script>
子组件
1.通过点击触发emit传值

<template>
<button @click="sendDataToParent">Send Data</button>
</template>

<script setup>
import { defineEmits } from 'vue';

const emits = defineEmits(['customEvent']);
//const emits = defineEmits('customEvent'); 这种写法也可以 但是必须defineEmits先定义函数

const sendDataToParent = () => {
emits('customEvent', 'Data from child');
};
// emits(父组件函数名,参数)
</script>

三、v-model 双向绑定
v-model 是一种简化的语法糖,用于实现父组件和子组件之间的双向数据绑定。

父组件

<template>
<ChildComponent v-model="parentValue" />
<p>{{ parentValue }}</p>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const parentValue = ref('Initial value');
</script>

子组件

<template>
<input v-model="localValue" @input="updateValue">
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';

const props = defineProps({
modelValue: String
});

const emits = defineEmits(['update:modelValue']);

const localValue = ref(props.modelValue);

const updateValue = () => {
emits('update:modelValue', localValue.value);
};
</script>

、、、、、、、、、、、、、、、
或者
<template>
<div class="childPage">
<button @click="updateA">按钮</button>
</div>
</template>

<script lang="ts" setup>
import { defineModel } from "vue";

const parentValue = defineModel({
type: Number,
default: 0,
});

const updateA = () => {
parentValue value += 1;
};
</script>

四、 provide/inject(跨层级组件传值)
此种方式,可以用于替代 window.location.reload 刷新页面以此规避页面闪白问题
provide 和 inject 用于在祖先组件和后代组件之间进行跨层级的数据传递,不需要一层一层地通过 Props 传递。 不管嵌套的再深都可以使用,但要注意,只适用父子组件,无嵌套关系的不能使用

例如:
父组件

const isRouterJump= ref(true); // 是否路由跳转

const reload = () => {
isRouterJump.value = false;
nextTick(() => {
isRouterJump.value = true
})
}
provide("reload", reload);
<template>
<ConfigGlobal >
<RouterView v-if="isRouterJump"/>
<routerSearch />
</ConfigGlobal>
</template>

子组件

<template>
<p>{{ injectedData }}</p>
</template>

<script setup>
import { inject } from 'vue';
const reload = inject<any>("reload");
reload ()
</script>

五、事件总线(mitt 库)第三方库
篇幅有限 在这里只介绍用法
使用第三方库 mitt 可以创建一个全局的事件总线,实现任意组件之间的通信。

事件总线
创建 useEmitt.js

import mitt from 'mitt';
const emitter = mitt();
export default emitter;

发送事件的组件示例:

<template>
<button @click="sendEvent">Send Event</button>
</template>

<script setup>
import emitter from './eventBus';

const sendEvent = () => {
emitter.emit('customEvent', 'Data from sender');
};
</script>

接收事件的组件示例:

<template>
<!-- 组件模板 -->
</template>

<script setup>
import { onMounted, onBeforeUnmount } from 'vue';
import emitter from './eventBus';

const handleEvent = (data) => {
console.log('Received data:', data);
};

onMounted(() => {
emitter.on('customEvent', handleEvent);
});

onBeforeUnmount(() => {
emitter.off('customEvent', handleEvent);
});
</script>

六、 Vuex 或 Pinia(状态管理库)
Pinia 示例:

import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});

使用 Store 的组件示例:

<template>
<p>{{ counterStore.count }}</p>
<button @click="counterStore.increment">Increment</button>
</template>

<script setup>
import { useCounterStore } from './store';

const counterStore = useCounterStore();
</script>

VUE3中的组件通信的更多相关文章

  1. vue学习笔记(九)vue-cli中的组件通信

    前言 在上一篇博客vue学习笔记(八)组件校验&通信中,我们学会了vue中组件的校验和父组件向子组件传递信息以及子组件通知父组件(父子组件通信),上一篇博客也提到那是对组件内容的刚刚开始,而本 ...

  2. Vue3 中的组件 provide和inject 传值、获取组件实例的方法getCurrentInstance()

    一. provide和inject(依赖注入) 1:在父级组件中提供数据           语法:provide('提供给子组件的变量名',提供给子组件的数据) 2: 在子级组件中获取收据     ...

  3. vue 中的组件通信

    vue中组件通信,一般分为三种情况,父与子,子与父,子子之间. 一.父与子通信 父组件将值传给子组件,一般通过props,设置默认的类型.调用的时候通过 xx=" ", 或者:XX ...

  4. Vue2中父子组件通信的几种常用方法

    源码地址 点击查看演示源码 Vue2父子传参:props 首先在父组件中引入子组件,然后以属性的方式将数据传递给子组件 父组件: <template> <div class=&quo ...

  5. vue2.0 $emit $on组件通信

    在vue1.0中父子组件通信使用$dispatch 和 $broadcast,但是在vue2.0中$dispatch 和 $broadcast 已经被弃用. 因为基于组件树结构的事件流方式实在是让人难 ...

  6. Vue3.x 关于组件的那些变化(新手必看篇)

    一.组件内的 data 为什么总是函数形式? 我们试着先做一个计数器案例,把 data 的返回形式修改成一个对象.具体的代码如下: <template> <div> <b ...

  7. Vue中组件通信的几种方法(Vue3的7种和Vue2的12种组件通信)

    Vue3组件通信方式: props $emit expose / ref $attrs v-model provide / inject Vuex 使用方法: props 用 props 传数据给子组 ...

  8. android中四大组件之间相互通信

    好久没有写有关android有关的博客了,今天主要来谈一谈android中四大组件.首先,接触android的人,都应该知道android中有四大组件,activity,service,broadca ...

  9. React中嵌套组件与被嵌套组件的通信

    前言 在React项目的开发中经常会遇到这样一个场景:嵌套组件与被嵌套组件的通信. 比如Tab组件啊,或者下拉框组件. 场景 这里应用一个最简单的Tab组件来呈现这个场景. import React, ...

  10. vue2.0s中eventBus实现兄弟组件通信

    在vue1.0中,组件之间的通信主要通过vm.$dispatch沿着父链向上传播和用vm.$broadcast向下广播来实现.然而在vue2.0中,已经废除了这种用法. vuex加入后,对组件之间的通 ...

随机推荐

  1. CentOS7安装RabbitMQ (安装包安装)

    环境: CentOS7 需要安装:erlang 22.2  rabbitmq 3.8.3 参考: rabbit官网地址:http://www.rabbitmq.com/which-erlang.htm ...

  2. CommonLang3-使用介绍

    学习要带着目的,参照现实问题 本次目标: 了解 CommonsLang3 API 文档,找对路后以后开发直接查询 API 文档,摈弃盲目的百度 掌握基础的字符串.日期.数值等工具方法,初步替代手搓的工 ...

  3. Ollama模型迁移

    技术背景 在前面的一些文章中,我们介绍过使用Ollama在Linux平台加载DeepSeek蒸馏模型,使用Ollama在Windows平台部署DeepSeek本地模型.除了使用Ollama与模型文件交 ...

  4. [BZOJ4605] 崂山白花蛇草水 题解

    突然想买一瓶,然后喝上几口.(不要命的想法) 动态全局 \(k\) 大想到权值线段树上二分. 由于要存储二维的点,所以得用到我们神通广大的 \(KDT\) 了. 那么想到权值线段树套 \(KDT\) ...

  5. 史陶比尔Stabli机器人维修小细节

    在工业自动化领域,史陶比尔机器人以其卓越的性能和可靠性而著称.然而,即使是尖端的设备,也难免会遇到Stabli机械手故障和问题.对于机器人维护和修理,每一个小细节都显得至关重要. 一.观察 首先,我们 ...

  6. iview weapp输入组件input事件顺序

    做小程序,使用ivew weapp组件框架,同时用到了i-input和i-modal,更具体说,就是在modal里面放置了input,填写数据后点击确定,实现提交数据. 出现点小问题,发现是事件顺序导 ...

  7. 【文献阅读】 PVDF &阻尼&有限元建模

    1. 压电Damper原理 Piezoelectric Composite Materials - ScienceDirect 当振动传递到压电材料时,振动能量通过压电效应转化为电能,产生交流电压.所 ...

  8. JMeter 获取 response body 的数据

    JMeter 获取 response body 的数据 位置:右键(HTTP Request) - Add - Post Processors - BeanShell PostProcessor im ...

  9. kvm内存优化--KSM

    一.KSM(Kernel SamePage Merging) 1.KSM简介 KSM允许内核在多个进程(包括虚拟机)之间共享完全相同的内存页,KSM让内核扫描检查正在运行中的程序并且比较他们的内存,若 ...

  10. docx4j转换pdf样式问题~Java Libreoffice转换pdf

    背景 本篇文章主要是介绍我在使用docx4j过程中遇到的问题,并最终如何通过Libreoffice来实现pdf的转换. 问题 在使用docx4j转换pdf过程中发现word文档中表格.加粗样式无法实现 ...