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

Vue 3.0 中provide常见使用场景

provide 和 inject 是 Vue 中用于跨组件传递数据的一对 API。provide 用于在祖先组件中提供数据,而 inject 用于在后代组件中注入这些数据。这种机制使得不需要通过一层一层的 props 传递数据,就可以在任何后代组件中获取祖先组件提供的数据。

在状态管理中,provide 和 inject 适用于一些全局或跨组件的数据共享场景,例如主题切换和语言切换。通过这对 API,可以在不依赖 Vuex 等状态管理工具的情况下,实现数据的全局共享和响应式更新。

1. 基本示例

父组件中:

<script setup>
import { ref, provide } from 'vue'
import { countSymbol } from './injectionSymbols'// 提供静态值
provide('path', '/project/')// 提供响应式的值
const count = ref(0)
provide('count', count)// 提供时将 Symbol 作为 key
provide(countSymbol, count)
</script>

子组件中:

<script setup>
import { inject } from 'vue'
import { countSymbol } from './injectionSymbols'// 注入不含默认值的静态值
const path = inject('path')// 注入响应式的值
const count = inject('count')// 通过 Symbol 类型的 key 注入
const count2 = inject(countSymbol)// 注入一个值,若为空则使用提供的默认值
const bar = inject('path', '/default-path')// 注入一个值,若为空则使用提供的函数类型的默认值
const fn = inject('function', () => {})// 注入一个值,若为空则使用提供的工厂函数
const baz = inject('factory', () => new ExpensiveObject(), true)
</script>

2. 主题换肤示例

2.1. 提供主题

在祖先组件中使用 provide 提供主题数据:

// App.vue
<template><div :class="currentTheme"><button @click="toggleTheme">Toggle Theme</button><ChildComponent /></div>
</template><script>
export default {data() {return {theme: 'light' // 默认主题};},computed: {currentTheme() {return this.theme == 'light' ? 'theme-light' : 'theme-dark';}},methods: {toggleTheme() {this.theme = this.theme === 'light' ? 'dark' : 'light';}},provide() {return {theme: this.theme};}
};
</script><style>
.theme-light {background-color: white;color: black;
}.theme-dark {background-color: black;color: white;
}
</style>

2.2. 使用主题

在后代组件中使用 inject 注入主题数据:

// ChildComponent.vue
<template><div><p>Current theme: {{ theme }}</p></div>
</template><script>
export default {inject: ['theme']
};
</script>

2.3. 更新主题 

为了使主题数据响应式,可以使用 Vue 的响应式机制,如 reactive 或 ref。下面是一个使用 ref 的例子:

// App.vue
<template><div :class="currentTheme"><button @click="toggleTheme">Toggle Theme</button><childComponent /></div>
</template><script>
import { ref, provide, computed } from 'vue';export default {setup() {const theme = ref('light');const toggleTheme = () => {theme.value = theme.value === 'light' ? 'dark' : 'light';};const currentTheme = computed(() => (theme.value === 'light' ? 'theme-light' : 'theme-dark'));provide('theme', theme);return {theme,toggleTheme,currentTheme};}
};
</script><style>
.theme-light {background-color: white;color: black;
}.theme-dark {background-color: black;color: white;
}
</style>

在子组件中:

// ChildComponent.vue
<template><div><p>Current theme: {{ theme }}</p></div>
</template><script>
import { inject } from 'vue';export default {setup() {const theme = inject('theme');return {theme};}
};
</script>

3. 语言切换示例

3.1. 提供语言

在祖先组件中使用 provide 提供语言数据:

// App.vue
<template><div><button @click="toggleLanguage">Toggle Language</button><childComponent /></div>
</template><script>
export default {data() {return {language: 'en' // 默认语言};},methods: {toggleLanguage() {this.language = this.language === 'en' ? 'fr' : 'en';}},provide() {return {language: this.language,translations: {en: {greeting: 'Hello'},fr: {greeting: 'Bonjour'}}};}
};
</script>

3.2. 使用语言

在后代组件中使用 inject 注入语言数据:

// ChildComponent.vue
<template><div><p>{{ translation.greeting }}</p></div>
</template><script>
export default {inject: ['language', 'translations'],computed: {translation() {return this.translations[this.language];}}
};
</script>

3.3.  更新语言

为了使语言数据响应式,可以使用 Vue 的响应式机制,如 reactive 或 ref。下面是一个使用 ref 的例子:

// App.vue
<template><div><button @click="toggleLanguage">Toggle Language</button><childComponent /></div>
</template><script>
import { ref, provide } from 'vue';export default {setup() {const language = ref('en');const toggleLanguage = () => {language.value = language.value === 'en' ? 'fr' : 'en';};const translations = {en: {greeting: 'Hello'},fr: {greeting: 'Bonjour'}};provide('language', language);provide('translations', translations);return {language,toggleLanguage};}
};
</script>

在子组件中:

// ChildComponent.vue
<template><div><p>{{ translation.greeting }}</p></div>
</template><script>
import { inject, computed } from 'vue';export default {setup() {const language = inject('language');const translations = inject('translations');const translation = computed(() => translations[language.value]);return {translation};}
};
</script>
http://www.xdnf.cn/news/9152.html

相关文章:

  • 一个开源的多播放源自动采集在线影视网站
  • GitCode镜像仓库批量下载开发实录
  • 【Redis】过期键删除策略,LRU和LFU在redis中的实现,缓存与数据库双写一致性问题,go案例
  • 第12次08: 省市县区三级联动收货地址
  • 沉石鱼惊旋
  • CVE-2021-44228源码分析与漏洞复现
  • Redis学习打卡-Day7-高可用(下)
  • 学习心得(19)如何验证Form表单里的数据是对的?
  • 并发基础|进程与线程
  • 使用NSIS 和 VNISEdit 打包 electron 程序为 exe 向导式安装包
  • 制药行业数字化转型:从挑战到智能化落地的实践路径
  • 嵌入式学习Day28
  • FreeRTOS——事件标志组
  • Java 权威方案:彻底修复 OPTIONS 方法安全漏洞(附企业级案例与测试指南)
  • 今日行情明日机会——20250526
  • 固态硬盘不识别或掉盘如何解决?——以Kingston FURY Renegade G5为例
  • Qwen-Agent的使用示例-天气查询(function calling)
  • 电子电路原理第十七章(线性运算放大器电路的应用)
  • 【登录优化】redis删除旧token
  • AI测试进入智能体时代:AutoGen 、 Coze、CrewAI 谁主沉浮?
  • C++ STL map multimap 查找操作详解
  • 2025-5-26Vue3快速上手
  • Nginx location匹配模式详解
  • 解锁 MCP 中的 JSON-RPC:跨平台通信的奥秘
  • nfs下载镜像报错File lookup fail,TTTTTTTTTTTTTTT,内核 6.11.0降到5.15.0
  • JAVA面试复习知识点
  • 【沉浸式解决问题】基于泛型递归,Java中实体类基类开启MybatisPlus的ActiveRecord模式
  • PID控制学习(位置式,增量式,算法优化,多环串级PID)
  • LitCTF 2025 Robbie Wanna Revenge
  • 并发的产生及对应的解决方案之实例举证