父级组件
<template> <div> <div @click="changeVlaue()"> 点击改变</div> </div> </template> import { reactive, provide, ref } from 'vue' setup() { const type= ref("business"); //加上响应式,加上后父组件改变此值所有子组件的值都会跟着变 //const type= "business"; //不加响应式,父组件调用了changeVlaue改变值后,子组件不会跟着一起改变 //const type= reactive({type:"business"}); //另一种响应式,用哪种都行,只是取值的方式不一样 provide('AssetsType', type) const methods = { changeVlaue: () => { type.value='我改变了' }, } return { ...toRefs(methods), type } }
子组件
<template> <div> <div> {{AssetsType}}</div> <div> {{test}}</div> </div> </template> import { reactive, inject, } from 'vue' setup() { //用法一 const test = inject('AssetsType') //用法二 const state: any = reactive({ AssetsType:inject('AssetsType') }) return { ...toRefs(state), test } }