Just read the practical tips on Vue shared by the author of VueUse at station B.

Purpose: Provide a read-only reactive variable in the root component instead of Vuex

Define the global variable interface

declare interface UserInfo {
    id: string,
    name: string
}
Copy the code

2. Initialize global variables

import { inject, reactive } from "vue";
import { InjectionKey } from "vue";
export const userinfoKey: InjectionKey<UserInfo> = Symbol(a)export const userinfoValue = reactive({ id: "123".name: "Zhang" })

export function useUserInfo() { return inject(userinfoKey) as UserInfo }

export function setUserInfo(user: UserInfo) {

    Object.assign(userinfoValue, { ... user }) }export default [userinfoKey, userinfoValue]
Copy the code

Vue. Use ()

import { App, readonly } from "vue";
import { userinfoKey, userinfoValue } from './UserInfo'

export default function createContext() {

    return {
        install(app: App) {

            app.provide(userinfoKey, readonly(userinfoValue))
            
        }

    }

}
Copy the code

4. Use in main.ts

app.use(createContext())

Copy the code

5. Use other components

import { useUserInfo, setUserInfo } from '.. /context/UserInfo'

const userinfo = useUserInfo() 
function updateuser() { setUserInfo({ ... userinfo,name: userinfo.name + "888"})}Copy the code