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

Vue3的多种组件通信方式

 父组件向子组件传递数据 (Props)

父组件

<template><child :name="name"></child>
</template><script setup>
import { ref } from 'vue'
import Child from './Child.vue'const name = ref('小明')
</script>

子组件

<template><div>{{ props.name }}</div>
</template><script setup>
import { defineProps } from 'vue'const props = defineProps({name: {type: String,default: '',},
})
</script>

子组件向父组件传递数据 (Emit)

子组件

<template><button @click="handleClick">点击我</button>
</template><script setup>
import { ref, defineEmits } from 'vue'const message = ref('来自子组件的问候')
const emits = defineEmits(['greet'])const handleClick = () => {emits('greet', message.value)
}
</script>

父组件

<template><child @greet="handleGreet"></child>
</template><script setup>
import { ref } from 'vue'
import Child from './Child.vue'const handleGreet = (message) => {console.log(message) // 输出: "来自子组件的问候"
}
</script>

兄弟组件通信 (Mitt)

npm install --save mitt

mainjs全局配置

import { createApp } from 'vue'
import mitt from 'mitt'
import App from './App.vue'const app = createApp(App)
app.config.globalProperties.$bus = mitt()app.mount('#app')

发送事件组件

<script setup>
import { getCurrentInstance } from 'vue'const { proxy } = getCurrentInstance()
const sendMessage = () => {proxy.$bus.emit('myEvent', '你好,兄弟')
}
</script>

接受事件组件

<script setup>
import { onMounted, getCurrentInstance } from 'vue'const { proxy } = getCurrentInstance()onMounted(() => {proxy.$bus.on('myEvent', (message) => {console.log(message) // 输出: "你好,兄弟"})
})
</script>

透传 Attributes ($attrs)

父组件

<template><child name="小明" age="18" hobby="篮球"></child>
</template>

子组件

<script setup>
import { useAttrs } from 'vue'const attrs = useAttrs()
console.log(attrs) // { age: "18", hobby: "篮球" }
</script>

模板引用 (Refs)

父组件

<template><child ref="childRef"></child><button @click="callChildMethod">调用子组件方法</button>
</template><script setup>
import { ref } from 'vue'
import Child from './Child.vue'const childRef = ref(null)const callChildMethod = () => {childRef.value.someMethod()
}
</script>

子组件

<script setup>
import { defineExpose } from 'vue'const someMethod = () => {console.log('子组件方法被调用了')
}defineExpose({someMethod,
})
</script>

双向绑定 (v-model)

父组件

<template><child v-model:name="name"></child>
</template><script setup>
import { ref } from 'vue'
import Child from './Child.vue'const name = ref('小明')
</script>

子组件

<template><input :value="name" @input="updateName" />
</template><script setup>
import { defineProps, defineEmits } from 'vue'const props = defineProps(['name'])
const emit = defineEmits(['update:name'])const updateName = (e) => {emit('update:name', e.target.value)
}
</script>

依赖注入 (Provide/Inject)

爷组件

<script setup>
import { provide, ref } from 'vue'const themeColor = ref('blue')
provide('theme', themeColor)
</script>

子孙组件

<script setup>
import { inject } from 'vue'const theme = inject('theme')
console.log(theme.value) // 'blue'
</script>

路由传参

通过query

import { useRouter } from 'vue-router'const router = useRouter()
router.push({ path: '/user', query: { id: 123 } })// 在目标组件中
import { useRoute } from 'vue-router'const route = useRoute()
console.log(route.query.id) // 123

Vuex 状态管理

// store/index.js
import { createStore } from 'vuex'export default createStore({state: {count: 0,},mutations: {increment(state) {state.count++},},
})// 在组件中使用
import { useStore } from 'vuex'const store = useStore()
console.log(store.state.count)
store.commit('increment')

Pinia 状态管理

// stores/counter.js
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', {state: () => ({ count: 0 }),actions: {increment() {this.count++},},
})// 在组件中使用
import { useCounterStore } from '@/stores/counter'const counter = useCounterStore()
console.log(counter.count)
counter.increment()

浏览器存储

localStorage 和 sessionStorage 可以用于在不同页面或组件之间共享数据。

// 存储数据
localStorage.setItem('user', JSON.stringify({ name: '小明', age: 18 }))// 读取数据
const user = JSON.parse(localStorage.getItem('user'))

Window 对象

// 设置全局数据
window.globalData = { message: '全局消息' }// 在任何地方使用
console.log(window.globalData.message)

 全局属性

Vue 3 提供了 app.config.globalProperties 来替代 Vue 2 中的 Vue.prototype,用于添加全局可用的属性。

// main.js
const app = createApp(App)
app.config.globalProperties.$http = axios// 在组件中使用
import { getCurrentInstance } from 'vue'const { proxy } = getCurrentInstance()
proxy.$http.get('/api/data')

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 解决C++读写中文乱码问题, UTF-8与GBK字符的转换 —基于Windows.h
  • RAR文件密码忘记怎么办?三大RAR密码找回工具推荐
  • 苹果macOS 15 Sequoia投屏功能 实现Mac上iPhone桌面管理
  • Windows下curl报错:curl: (3) unmatched close brace/bracket in URL position x
  • 【现代通信技术】走进现代通信系统架构
  • 海康相机二次开发学习笔记1-环境配置
  • 【2024】k8s集群 图文详细 部署安装使用(两万字)
  • Oracle笔记
  • 二叉树详解(1)
  • 【hexo博客问题】
  • 跨境电商测评网络:美国住宅IP的获取与使用
  • Golang 与 Java:编程语言比较及如何选择
  • 2024.8.15(python管理mysql、Mycat实现读写分离)
  • 【SpringCloud】RabbitMQ——五种方式实现发送和接收消息
  • Java后端面试题(redis相关2)(day8)
  • EOS是什么
  • interface和setter,getter
  • isset在php5.6-和php7.0+的一些差异
  • Perseus-BERT——业内性能极致优化的BERT训练方案
  • redis学习笔记(三):列表、集合、有序集合
  • ViewService——一种保证客户端与服务端同步的方法
  • Vue实战(四)登录/注册页的实现
  • Webpack入门之遇到的那些坑,系列示例Demo
  • 汉诺塔算法
  • 每天10道Java面试题,跟我走,offer有!
  • 排序算法之--选择排序
  • 前端js -- this指向总结。
  • 阿里云重庆大学大数据训练营落地分享
  • 如何通过报表单元格右键控制报表跳转到不同链接地址 ...
  • 移动端高清、多屏适配方案
  • ​Redis 实现计数器和限速器的
  • !$boo在php中什么意思,php前戏
  • ## 基础知识
  • #NOIP 2014#day.2 T1 无限网络发射器选址
  • #设计模式#4.6 Flyweight(享元) 对象结构型模式
  • (1/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序
  • (7)STL算法之交换赋值
  • (bean配置类的注解开发)学习Spring的第十三天
  • (Redis使用系列) SpringBoot中Redis的RedisConfig 二
  • (附源码)springboot 个人网页的网站 毕业设计031623
  • (附源码)ssm本科教学合格评估管理系统 毕业设计 180916
  • (十六)一篇文章学会Java的常用API
  • .bat批处理出现中文乱码的情况
  • .NET Entity FrameWork 总结 ,在项目中用处个人感觉不大。适合初级用用,不涉及到与数据库通信。
  • .NET 发展历程
  • .NET 项目中发送电子邮件异步处理和错误机制的解决方案
  • .NET中的十进制浮点类型,徐汇区网站设计
  • .secret勒索病毒数据恢复|金蝶、用友、管家婆、OA、速达、ERP等软件数据库恢复
  • @NoArgsConstructor和@AllArgsConstructor,@Builder
  • @德人合科技——天锐绿盾 | 图纸加密软件有哪些功能呢?
  • [10] CUDA程序性能的提升 与 流
  • [Android实例] 保持屏幕长亮的两种方法 [转]
  • [Angularjs]asp.net mvc+angularjs+web api单页应用
  • [C/C++]关于C++11中的std::move和std::forward
  • [C++] 默认构造函数、参数化构造函数、拷贝构造函数、移动构造函数及其使用案例