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

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>

相关文章:

  • 利用 `ngx_http_xslt_module` 实现 NGINX 的 XML → HTML 转换
  • Elasticsearch 如何实现跨数据中心的数据同步?
  • 【md2html python 将 Markdown 文本转换为 HTML】
  • Leetcode 25. K 个一组翻转链表
  • React JSX语法介绍(JS XML)(一种JS语法扩展,允许在JS代码中编写类似HTML的标记语言)Babel编译
  • Spring AI(一)
  • 两种调度Dify工作流的解决方案
  • UBUNTU20.04 配置以QT界面程序代替系统界面启动,以及如何在tty模式下以linuxfb形式启动
  • Java设计模式之代理模式详解
  • 大型三甲医院更换HIS系统全流程分析与经验考察(上)
  • 数据分析实战1(Excel制作报表)
  • Linux系统编程-DAY06
  • Opigno LMS 3.2.7 安装操作记录
  • pyspark实践
  • 火柴INIBOX专业矿机登场,碾压现有Initverse挖矿设备
  • YOLOv4:目标检测的新标杆
  • Pytest自动化测试框架搭建:Jenkins持续集成
  • AI学习搭档:开启终身学习新时代
  • torch cuda 版本安装
  • 【Java】DelayQueue
  • 企业门户网站建设与发展/推广普通话宣传内容
  • 北京市工程建设交易信息网站/长沙网站seo哪家公司好
  • 手机做网站用什么软件/seo的优点有哪些
  • 房地产做网站/网络推广工具和方法
  • 发布广告/沈阳seo技术
  • 网站建设关键词/关键词优化工具