组件十大传值

news2025/2/28 10:33:33

一、defineProps 和 defineEmits

defineProps 用于定义子组件接收的 props,即父组件传递给子组件的数据。

  1. 接收父组件传递的数据:定义子组件可以接受的属性及其类型。
  2. 类型检查:确保传递的数据符合预期的类型。

defineEmits 用于定义子组件可以触发的事件,从而向父组件传递数据或通知父组件发生了某些操作。

  1. 触发事件:子组件可以通过触发事件来通知父组件。
  2. 传递数据:事件可以携带数据传递给父组件
//父组件:
<template>
  <ChildComponent :message="parentMessage" @childEvent="handleChildEvent" />
</template>

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

const parentMessage = ref('Hello from Parent');

const handleChildEvent = (message) => {
  console.log('Received from child:', message);
};
</script>
//子组件
<template>
  <div>
    {{ message }}
    <button @click="sendMessageToParent">Send Message to Parent</button>
  </div>
</template>

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

const props = defineProps({
  message: String,
  default:''
});

const emit = defineEmits(['childEvent']);

const sendMessageToParent = () => {
  emit('childEvent', 'Hello from Child');
};
</script>

二、v-model

双向数据绑定

// 父组件
<template>
  <ChildComponent v-model="parentMessage" />
</template>

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

const parentMessage = ref('Hello from Parent');
</script>
// 子组件
<template>
  <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>

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

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

const emit = defineEmits(['update:modelValue']);
</script>

自定义 v-model 的 prop 和 event 名称

// 父组件
<template>
  <ChildComponent v-model:title="parentTitle" />
</template>

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

const parentTitle = ref('Hello from Parent');
</script>
// 子组件
<template>
  <input :value="title" @input="$emit('update:title', $event.target.value)" />
</template>

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

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

const emit = defineEmits(['update:title']);
</script>

三、refs

直接访问子组件实例或 DOM 元素,即操作dom节点。

// 父组件
<template>
  <ChildComponent ref="childRef" />
  <button @click="callChildMethod">Call Child Method</button>
</template>

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

const childRef = ref(null);

const callChildMethod = () => {
  childRef.value.childMethod(); // Child method called
  console.log(childRef.value.name) // panda
};
</script>
// 子组件
<template>
  <div>Child Component</div>
</template>

<script setup>
const childMethod = () => {
  console.log('Child method called');
};
const name=ref('panda')
defineExpose({
  childMethod,
  name,
});
</script>

四、provide 和 inject

祖先组件向后代组件传递数据,适用于多层级组件之间共享数据传值,从而减少 props 钓鱼(prop drilling)的问题

<template>
  <div>
    <h1>父组件</h1>
    <p>提供的消息: {{ parentMessage }}</p>
    <IntermediateComponent />
  </div>
</template>

<script setup>
import { provide, ref } from 'vue';
import IntermediateComponent from './IntermediateComponent.vue';

// 定义要提供的数据
const parentMessage = ref('Hello from Parent');

// 使用 provide 提供数据
provide('parentMessage', parentMessage);
</script>

<style scoped>
/* 样式可以根据需要添加 */
</style>
//中间组件-子组件
<template>
  <div>
    <h2>中间层组件</h2>
    <ChildComponent />
  </div>
</template>

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

<style scoped>
/* 样式可以根据需要添加 */
</style>
<template>
  <div>
    <h3>子组件</h3>
    <p>接收到的消息: {{ receivedMessage }}</p>
  </div>
</template>

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

// 使用 inject 接收父组件提供的数据
const receivedMessage = inject('parentMessage');
</script>

<style scoped>
/* 样式可以根据需要添加 */
</style>

五、 路由传参

Query

通过 URL 查询参数传递数据

// 父组件
<template>
  <router-link :to="{ name: 'Child', query: { message: 'Hello from Parent' } }">Go to Child</router-link>
</template>
// 子组件
<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { useRoute } from 'vue-router';

const route = useRoute();
const message = route.query.message;
</script>

Params

通过 URL 参数传递数据

// 父组件
<template>
  <router-link :to="{ name: 'Child', params: { id: 123 } }">Go to Child</router-link>
</template>
//子组件
<template>
  <div>ID: {{ id }}</div>
</template>

<script setup>
import { useRoute } from 'vue-router';

const route = useRoute();
const id = route.params.id;
</script>

State

通过路由状态传递数据

//父组件
<template>
  <router-link :to="{ name: 'Child', state: { message: 'Hello from Parent' } }">Go to Child</router-link>
</template>
// 子组件
<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { useRoute } from 'vue-router';

const route = useRoute();
const message = route.state?.message || '';
</script>

六、Pinia

vue3状态管理

// Pinia Store
import { defineStore } from 'pinia';

export const useMainStore = defineStore('main', {
  state: () => ({
    message: 'Hello from Pinia'
  }),
  actions: {
    updateMessage(newMessage) {
      this.message = newMessage;
    }
  }
});
// 父组件
<template>
  <div>{{ message }}</div>
  <button @click="updateMessage">Update Message</button>
</template>

<script setup>
import { useMainStore } from '../stores/main';

const store = useMainStore();

const message = store.message;

const updateMessage = () => {
  store.updateMessage('Updated Message');
};
</script>

七、 浏览器缓存localStorage 或 sessionStorage

// 父组件
<template>
  <div>{{ cachedMessage }}</div>
  <input v-model="cachedMessage" @input="saveMessage" />
</template>

<script setup>
import { ref, onMounted } from 'vue';

const cachedMessage = ref(localStorage.getItem('message') || '');

const saveMessage = () => {
  localStorage.setItem('message', cachedMessage.value);
};

onMounted(() => {
  cachedMessage.value = localStorage.getItem('message') || '';
});
</script>

八、 window 对象全局挂载

// 父组件
<template>
  <div>{{ globalMessage }}</div>
  <input v-model="globalMessage" @input="updateGlobalMessage" />
</template>

<script setup>
import { ref, onMounted } from 'vue';

const globalMessage = ref(window.globalMessage || '');

const updateGlobalMessage = () => {
  window.globalMessage = globalMessage.value;
};

onMounted(() => {
  globalMessage.value = window.globalMessage || '';
});
</script>

九、兄弟组件传值 (mitt)

// 安装 mitt
npm install mitt
// 创建事件总线
// eventBus.js
import mitt from 'mitt';

export const emitter = mitt();
// 兄弟A
<template>
  <button @click="sendMessageToSibling">Send Message to Sibling</button>
</template>

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

const sendMessageToSibling = () => {
  emitter.emit('siblingEvent', 'Hello from Sibling A');
};
</script>
// 兄弟B
<template>
  <div>{{ message }}</div>
</template>

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

const message = ref('');

const handleMessage = (msg) => {
  message.value = msg;
};

onMounted(() => {
  emitter.on('siblingEvent', handleMessage);
});

onUnmounted(() => {
  emitter.off('siblingEvent', handleMessage);
});
</script>

十、$attrs

  1. 透传属性: 将父组件传递的所有非 prop 属性自动应用到子组件的根元素或其他指定元素上。
  2. 样式和类: 传递 class 和 style 属性,以便子组件能够继承父组件的样式。
  3. 事件监听器: 传递事件监听器,使得子组件能够响应父组件传递的事件。
// 父组件
<template>
  <ChildComponent class="parent-class" style="color: red;" custom-attr="custom-value" @click="handleClick" />
</template>

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

const handleClick = () => {
  console.log('Clicked on ChildComponent');
};
</script>
// 子组件
<template>
  <div v-bind="$attrs">
    Child Component
  </div>
</template>

<script setup>
// 子组件不需要显式声明父组件传递的属性
</script>

<style scoped>
.parent-class {
  background-color: yellow;
}
</style>

默认情况下,Vue 会将 $attrs 应用到子组件的根元素上。如果你不希望这样做,可以通过设置 inheritAttrs: false 来禁用这个行为。

// 子组件
<template>
  <div>
    <span v-bind="$attrs">Child Component</span>
  </div>
</template>

<script setup>
// 禁用自动应用 $attrs 到根元素
defineOptions({
  inheritAttrs: false
});
</script>

如果想访问$attrs对象

// 子组件
<template>
  <div>
    <span v-bind="filteredAttrs">Child Component</span>
  </div>
</template>

<script setup>
import { useAttrs, computed } from 'vue';

const attrs = useAttrs();

const filteredAttrs = computed(() => {
  // 过滤掉不需要的属性
  return Object.fromEntries(
    Object.entries(attrs).filter(([key]) => !['custom-attr'].includes(key))
  );
});
</script>

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

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

相关文章

WPF 依赖属性和附加属性

除了普通的 CLR 属性&#xff0c; WPF 还有一套自己的属性系统。这个系统中的属性称为依赖属性。 1. 依赖属性 为啥叫依赖属性&#xff1f;不叫阿猫阿狗属性&#xff1f; 通常我们定义一个普通 CLR 属性&#xff0c;其实就是获取和设置一个私有字段的值。假设声明了 100 个 …

递归实现指数型枚举(递归)

92. 递归实现指数型枚举 - AcWing题库 每个数有选和不选两种情况 我们把每个数看成每层&#xff0c;可以画出一个递归搜索树 叶子节点就是我们的答案 很容易写出每dfs函数 dfs传入一个u表示层数 当层数大于我们n时&#xff0c;去判断每个数字的选择情况&#xff0c;输出被选…

mac 安装graalvm

Download GraalVM 上面链接选择jdk的版本 以及系统的环境下载graalvm的tar包 解压tar包 tar -xzf graalvm-jdk-<version>_macos-<architecture>.tar.gz 移入java的文件夹目录 sudo mv graalvm-jdk-<version> /Library/Java/JavaVirtualMachines 设置环境变…

【WPS安装】WPS编译错误总结:WPS编译失败+仅编译成功ungrib等

WPS编译错误总结&#xff1a;WPS编译失败仅编译成功ungrib等 WPS编译过程问题1&#xff1a;WPS编译失败错误1&#xff1a;gfortran: error: unrecognized command-line option ‘-convert’; did you mean ‘-fconvert’?解决方案 问题2&#xff1a;WPS编译三个exe文件只出现u…

Redis 集群实操:强大的数据“分身术”

目录 Redis Cluster集群模式 1、介绍 2、架构设计 3、集群模式实操 4、故障转移 5、常用命令 Redis Cluster集群模式 1、介绍 redis3.0版本推出的Redis Cluster 集群模式&#xff0c;每个节点都可以保存数据和整个集群状态&#xff0c;每个节点都和其他所有节点连接。Cl…

数据结构day5:单向循环链表 代码作业

一、loopLink.h #ifndef __LOOPLINK_H__ #define __LOOPLINK_H__#include <stdio.h> #include <stdlib.h>typedef int DataType;typedef struct node {union{int len;DataType data;};struct node* next; }loopLink, *loopLinkPtr;//创建 loopLinkPtr create();//…

植物大战僵尸杂交版v3.0.2最新版本(附下载链接)

B站游戏作者潜艇伟伟迷于12月21日更新了植物大战僵尸杂交版3.0.2版本&#xff01;&#xff01;&#xff01;&#xff0c;有b站账户的记得要给作者三连关注一下呀&#xff01; 不多废话下载链接放上&#xff1a; 夸克网盘链接&#xff1a;&#xff1a;https://pan.quark.cn/s/5c…

Unity 圆形循环复用滚动列表

一.在上一篇垂直循环复用滚动列表的基础上&#xff0c;扩展延申了圆形循环复用滚动列表。实现此效果需要导入垂直循环复用滚动列表里面的类。 1.基础类 using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using …

京东大数据治理探索与实践 | 京东零售技术实践

01背景和方案 在当今的数据驱动时代&#xff0c;数据作为关键生产要素之一&#xff0c;其在商业活动中的战略价值愈加凸显&#xff0c;京东也不例外。 作为国内领先的电商平台&#xff0c;京东在数据基础设施上的投入极为巨大&#xff0c;涵盖数万台服务器、数 EB 级存储、数百…

android:sharedUserId 应用进程声明介绍

背景 adb install 安装系统软件报错,原因是签名不一致,进程改变。 代码分析 AndroidManifest.xml 定义的 android:sharedUserId 应用归属进程不同,从phone切换到system。 初始配置 <manifest xmlns:android="http://schemas.android.com/apk/res/android"c…

Liveweb视频融合共享平台在果园农场等项目中的视频监控系统搭建方案

一、背景介绍 在我国的大江南北遍布着各种各样的果园&#xff0c;针对这些地处偏僻的果园及农场等环境&#xff0c;较为传统的安全防范方式是建立围墙&#xff0c;但是仅靠围墙仍然无法阻挡不法分子的有意入侵和破坏&#xff0c;因此为了及时发现和处理一些难以察觉的问题&…

交换机链路聚合(手动负载分担模式)(eNSP)

目录 交换机SW_C配置: 交换机-PC划分vlan: 交换机-交换机端口聚合: 交换机SW_D配置: 交换机-PC划分vlan: 交换机-交换机端口聚合: 验证: 链路聚合的端口清除: 交换机端口聚合的存在意义主要有以下几点: 增加带宽 提高冗余性和可靠性 实现负载均衡 降低成本 …

玩转树莓派Pico(19): 迷你气象站5——软件整合

一、前言 各个模块都已经测试了&#xff0c;硬件也组装完成&#xff0c;到了软件整合的步骤了。 目前我仅按照自己的经验来整合&#xff0c;肯定要踩坑的。以后除了多去开源网站看看大佬的代码&#xff0c;还要继续揣摩《无线电》杂志里的文章。很多文章对我来说比较高深&#…

30. 多进程编程

一、什么是进程 进程&#xff08;process&#xff09;则是一个执行中的程序。每个进程都拥有自己的地址空间、内存、数据栈以及其它用于跟踪执行的辅助数据。操作系统管理其上所有进程的执行&#xff0c;并为这些进程合理分配时间。进程也可以通过派生新的进程来执行其它任务&a…

Unity Post请求发送fromdata数据content-type

wwwfrom 的 headers["Content-Type"]修改 错误代码&#xff1a; WWWForm form new WWWForm(); if (form.headers.ContainsKey("Content-Type")) {string boundary string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));form…

aosp15 - Activity生命周期切换

本文探查的是&#xff0c;从App冷启动后到MainActivity生命周期切换的系统实现。 调试步骤 在com.android.server.wm.RootWindowContainer#attachApplication 方法下断点&#xff0c;为了attach目标进程在com.android.server.wm.ActivityTaskSupervisor#realStartActivityLock…

SAP PP ECN CSAP_MAT_BOM_MAINTAIN

刚开始的时候ECN总是加不上&#xff0c; 参考kimi给出的案例 点击链接查看和 Kimi 智能助手的对话 https://kimi.moonshot.cn/share/cth1ipmqvl7f04qkggdg 效果 加上了 FUNCTION ZPBOM_PLM2SAP. *"------------------------------------------------------------------…

GitLab的安装和使用

1.GitLab 环境说明 系统版本 CentOS 7.2 x86_64 软件版本 gitlab-ce-10.8.4 GitLab 是一个用于仓库管理系统的开源项目&#xff0c;使用Git作为代码管理工具&#xff0c;并在此基础上搭建起来的web服务。可通过Web界面进行访问公开的或者私人项目。它拥有与Github类似的功能…

开放词汇目标检测(Open-Vocabulary Object Detection, OVOD)综述

定义 开放词汇目标检测&#xff08;Open-Vocabulary Object Detection, OVOD&#xff09;是一种目标检测任务&#xff0c;旨在检测和识别那些未在训练集中明确标注的物体类别。传统的目标检测模型通常只能识别有限数量的预定义类别&#xff0c;而OVOD模型则具有识别“开放词汇…

JaxaFx学习(三)

目录&#xff1a; &#xff08;1&#xff09;JavaFx MVVM架构实现 &#xff08;2&#xff09;javaFX知识点 &#xff08;3&#xff09;JavaFx的MVC架构 &#xff08;4&#xff09;JavaFx事件处理机制 &#xff08;5&#xff09;多窗体编程 &#xff08;6&#xff09;数据…