vue3的api解读-provide inject

文章介绍了Vue框架中的Context概念,以及如何使用Provide和Inject进行父子组件间的通信和全局状态管理。通过示例代码展示了如何设置和获取Context,讨论了Provide/Inject的优缺点,并提出了替代方案——使用消息传递机制。
摘要由CSDN通过智能技术生成

目录

什么是context

Provide/Inject和Context

provide inject示例讲解

provide / inject api

/src/examples/ProvideExamples.tsx


什么是context

  • Context(上下文),是实体间共享的知识。
      • 举例1:this指针
      • 举例2:浏览器执行环境中的window对象
      • 举例3:前端系统的全局用户登录状态

Provide/Inject和Context

Vue提供上下文的方式

  • Provide
      • 向子组件提供Context
  • Inject
      • 从Context中获取数据

provide inject示例讲解

provide / inject api

  • Coding:将Provide / Inject模型为全局提供用户状态

/src/examples/ProvideExamples.tsx

import { defineComponent, provide, inject, reactive } from "vue";
type Theme = {
  color: string
}
export const ProvideExample01 = defineComponent({
  setup() {
    const theme = reactive({
      color: "red"
    })
    provide("theme", theme)
    return () => {
      return (<div>
        <button onClick={() => {
          theme.color = "blue"
        }}>Change Theme to Blue</button>
        <button onClick={() => {
          theme.color = "red"
        }}>Change Theme to Red</button>
        <A />
      </div>
      )
    }
  }
})
const B = defineComponent({ // 子组件
  setup() {
    const theme = inject("theme") as Theme
    return () => {
      return <div style={{
        backgroundColor: theme.color
      }}>
        {theme.color}
      </div>
    }
  }
})
const A = () => { // 父元素
  return <B />
}
function wait(ms: number) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(null)
    }, ms)
  })
}
async function login() {
  await wait(2000)
  return {
    success: true,
    data: null
  }
}
type User = {
  username: string,
  loggedIn: boolean
}
function useUserContext() {
  const user = reactive<User>({
    username: "",
    loggedIn: false
  })
  provide("user", user)
  login().then(() => {
    user.username = "youdao"
    user.loggedIn = true
  })
}
export const ProvideExample02 = defineComponent({
  setup() {
    useUserContext()
    return () => {
      return <div>
        <Header />
        <Content />
      </div>
    }
  }
})
const Header = defineComponent({
  setup() {
    // const user = inject("user") as User
    const user = inject<User>("user")!// !非空断言
    return () => {
      return <header>登录用户——<strong>{user.username}</strong></header>
    }
  }
})
const Content = () => {
  return <div>你好!</div>
}

思考:

1.Provide / Inject的缺点是什么?缺少类型;如provide传的是给string,inject收到的是个unknown

2.可不可以用 Provide / Inject 进行跨组件传参?

                技术上可以,要是参数不是共享的context;语义上不易读。不建议这样用;耦合,违反最小知识原则

3. 如果不用Provide / Inject 我们应该怎么做?可以用发消息

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值