import { provide,inject } from 'vue'
provide
:将父组件的数据传递给所有子组件(子孙都有)inject
:接收provide
项目文件结构
App.vue
是Header.vue
的父组件,Header.vue
是Nav.vue
的父组件
传值过程
App.vue
<template><h2>App.vue-Top组件</h2><p>user:{{ user }}</p><button @click="userAdd">添加用户</button><hr><Header />
</template><script setup>
import { ref, reactive ,provide} from "vue";
import Header from "./components/Header.vue";let user = ref(0);const web = reactive({name: "1234567890",url: "https://www.1234567890.com"
})const userAdd = () => {user.value += 1;
}provide("provideWeb", web)
provide("provideUser", user)
provide("provideFuncUserAdd", userAdd)</script><style lang="scss" scoped></style>
Header.vue
<template><h2>header Middle组件</h2><p>接收App组件的user数据:{{ user }}</p><hr><Nav/>
</template><script setup>
import { inject } from 'vue'
import Nav from './Nav.vue'const user = inject('provideUser')
</script><style lang="scss" scoped></style>
Nav.vue
<template><h2>nav.vue Bottom组件</h2><p>接收App组件的web数据:{{ web }}</p><button @click="userAdd()">添加用户</button></template><script setup>
import { inject } from 'vue'const web = inject('provideWeb')
const userAdd = inject('provideFuncUserAdd')
</script><style lang="scss" scoped></style>
参考
https://www.bilibili.com/video/BV1nV411Q7RX