inject 和provide 的用法之实现监听sessionStorage的变化做对应操作

一、inject 和provide 的用法

inject 和 provide 是 Vue 3 中的依赖注入机制,用于在组件树中传递数据,而不需要通过 props 逐级传递

1. 基本用法
复制代码
// 父组件
import { provide } from 'vue'

const message = ref('Hello')
provide('key', message)

// 子组件
import { inject } from 'vue'

const message = inject('key')
2. 使用 Symbol 作为 key(推荐)
复制代码
// types.ts
export const MESSAGE_KEY = Symbol()

// 父组件
import { MESSAGE_KEY } from './types'
provide(MESSAGE_KEY, message)

// 子组件
import { MESSAGE_KEY } from './types'
const message = inject(MESSAGE_KEY)
3. 提供默认值
复制代码
const message = inject('key', '默认值')
4. 类型声明:
复制代码
interface MessageContext {
  message: Ref<string>
  updateMessage: (value: string) => void
}

// 父组件
provide<MessageContext>('messageContext', {
  message,
  updateMessage: (value) => { message.value = value }
})

// 子组件
const { message, updateMessage } = inject<MessageContext>('messageContext')!
5. 只读数据
复制代码
import { readonly } from 'vue'

provide('count', readonly(count))

二、注意事项

  • provide 和 inject 绑定不是响应式的。但如果你传递了一个响应式对象,那么它的属性仍然是响应式的。
  • 尽量在 setup() 函数中使用 provide 和 inject。
  • 不要在子组件中修改注入的值,除非父组件明确允许。
  • 使用 Symbol 作为 key 可以避免命名冲突。
  • 考虑使用 TypeScript 来增强类型安全。
  • 使用 provide 和 inject 可以简化组件间的数据传递,特别是对于深层嵌套的组件结构。但也要注意不要过度使用,以免使数据流变得难以追踪。

三、案例代码

要实现点击 tab 获取最新的 sessionStorage.getItem('activeTabType'),可以按以下步骤修改代码:

  1. 修改 getActiveTabType 计算属性

    const getActiveTabType = computed(() => {
    return sessionStorage.getItem('activeTabType') || '';
    });

  2. 在 AggregateAnalysisTab(子组件) 组件中,当 tab 被点击时,更新 sessionStorage:

    // 在 AggregateAnalysisTab.vue 中
    const handleTabClick = (tabType: string) => {
    sessionStorage.setItem('activeTabType', tabType);
    };

  3. 在父组件中添加一个响应式变量来触发重新计算:

    const tabUpdateTrigger = ref(0);

    const getActiveTabType = computed(() => {
    tabUpdateTrigger.value; // 添加这行来依赖这个变量
    return sessionStorage.getItem('activeTabType') || '';
    });

  4. 使用 provide/inject 或事件总线在 AggregateAnalysisTab 中通知父组件更新:

    // 在父组件中
    provide('updateTabType', () => {
    tabUpdateTrigger.value++;
    });

    // 在 AggregateAnalysisTab.vue 中
    const updateTabType = inject('updateTabType');

    const handleTabClick = (tabType: string) => {
    sessionStorage.setItem('activeTabType', tabType);
    updateTabType();
    };

这样,每次点击 tab 时,sessionStorage 会被更新,并且父组件的 getActiveTabType 计算属性会重新计算,获取最新的值。

四、类型问题

如: "updateTabType"的类型为"未知"

  1. 在父组件中定义 updateTabType 的类型:

    type UpdateTabType = () => void;

    // 在父组件中
    const updateTabType: UpdateTabType = () => {
    tabUpdateTrigger.value++;
    };

    provide('updateTabType', updateTabType);

  2. 在 子组件 AggregateAnalysisTab.vue 中,我们可以这样使用 inject:

    import { inject } from 'vue';

    type UpdateTabType = () => void;

    const updateTabType = inject('updateTabType') as UpdateTabType;

相关推荐
毕设源码-朱学姐5 小时前
【开题答辩全过程】以 工厂能耗分析平台的设计与实现为例,包含答辩的问题和答案
java·vue.js
老前端的功夫6 小时前
Vue 3 性能深度解析:从架构革新到运行时的全面优化
javascript·vue.js·架构
天天扭码6 小时前
如何实现流式输出?一篇文章手把手教你!
前端·aigc·ai编程
前端 贾公子7 小时前
vue移动端适配方案 === postcss-px-to-viewport
前端·javascript·html
GISer_Jing8 小时前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼8 小时前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长9 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs9 小时前
Nginx核心架构设计
运维·前端·nginx
雪球工程师团队9 小时前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程