下面是一个使用 provide
和 inject
实现跨层级组件通信的示例,展示了一个主题切换功能,其中顶层组件提供主题配置,深层嵌套组件可以直接获取这些配置:
<template>
<div :class="`theme-${currentTheme}`">
<h1>Provide/Inject 示例</h1>
<button @click="toggleTheme">切换主题</button>
<ParentComponent />
</div>
</template>
<script>
import { provide, ref } from 'vue'
import ParentComponent from './ParentComponent.vue'
export default {
components: { ParentComponent },
setup() {
// 定义响应式的主题变量
const currentTheme = ref('light')
// 切换主题的方法
const toggleTheme = () => {
currentTheme.value = currentTheme.value === 'light' ? 'dark' : 'light'
}
// 提供主题相关的数据和方法
provide('themeConfig', {
currentTheme,
toggleTheme
})
return {
currentTheme,
toggleTheme
}
}
}
</script>
<style>
.theme-light {
background-color: white;
color: black;
}
.theme-dark {
background-color: #333;
color: white;
}
button {
padding: 8px 16px;
margin: 20px 0;
cursor: pointer;
}
</style>
这个示例包含三个组件,形成了 App -> ParentComponent -> ChildComponent
的嵌套关系:
provide
提供了 themeConfig
对象,包含响应式的 currentTheme
和 toggleTheme
方法provide/inject
的优势:中间组件无需关心传递的数据inject
获取顶层提供的 themeConfig
ref
实现了数据响应式,主题切换时所有组件会自动更新这个模式特别适合实现主题、权限、语言等需要全局共享的功能。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。