1、provide和inject
提供一个值,可以在应用中的所有后代组件注入使用。不论组件嵌套多深,父组件都可以为所有子组件或孙组件提供数据,父组件使用 provide 提供数据,子组件或孙组件 inject 注入数据。同时兄弟组件之间传值更方便。
provide 函数接收两个参数:
provide( name,value )
name:定义提供property的name。value:property的值。
import { provide } from "vue"
<script lang="ts" setup>
provide('info',"值")
</script>
inject 函数有两个参数:
inject(name,default)
name:接收provide提供的属性名。default:设置默认值,可以不写,是可选参数。
import { inject } from "vue"
<script lang="ts" setup>
inject('info',"设置默认值")
</script>
2、兄弟组件之间传值
vue3中的小项目中,推荐使用第三方库来实现 mitt
install
安装 npm i mitt -S
Usage
mitt API方法有三个emit、on、off
import mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.all.clear()
// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo) // listen
emitter.off('foo', onFoo) // unlisten
main.ts全局引用一下
import mitt from 'mitt'
const Mit = mitt()
const app = createApp(App)
declare module 'vue'{
export interface ComponentCustomProperties {
$Bus:typeof Mit
}
}
app.config.globalProperties.$Bus = Mit
A组件中使用
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();
const switchBtn = () => {
instance?.proxy?.$Bus.emit("hello", "mitt");
};
B组件中拿到
import { getCurrentInstance, ref } from "vue";
let flag = ref(null);
const instance = getCurrentInstance();
instance?.proxy?.$Bus.on("hello", (str: any) => {
console.log(str);
flag.value = str;
});