当数据要穿透四五层组件时,props 层层转发既繁琐又污染中间组件,此时 provide 与 inject 派上用场。祖先组件用 provide 提供值(组合式 API 中通常包成 readonly 的 ref),任意深度的后代组件用 inject 按名取用,中间组件完全无感。
它最常见的应用是主题、本地化文案、全局尺寸配置等横切关注点。需要注意 inject 到的数据默认不是响应式的:要么提供 ref 或 reactive 对象本身,要么用函数让后代主动拉取。同时尽量用 readonly 包一层,避免后代组件随意篡改源头造成调试困难。
// 祖先组件 import { provide, ref, readonly } from 'vue'; const theme = ref('dark'); provide('theme', readonly(theme)); // 任意层级的后代组件 const theme = inject('theme', 'light'); // 第二个参数是默认值 console.log('当前主题:' + theme.value);