Recently writing a Vue 3 project using provide/inject, so make a learning note.
Need: Click the logo on the top bar to toggle the sidebar show or hide.
Ideas:
- A variable is required to record the display or hiding of the sidebar.
- Variables cannot be placed in either the top bar or the sidebar because the two components are not accessible to each other.
- Put where? Their ancestor: App.vue.
steps
- Use provide to mark variables in app.vue,
- Use Inject to access variables in the sidebar, top bar
// App.vue
<script lang="ts">
import { provide, ref } from 'vue'
export default {
name: 'App',
setup(){
const menuVisible = ref(true)
provide('menuVisible',menuVisible)
}
}
</script>
Copy the code
At the top of the column
<script lang="ts"> import { inject, Ref } from "vue"; export default { setup() { const menuVisible = inject<Ref<boolean>>("menuVisible"); // <Ref< Boolean >> Const toggleMenu = () => {menuVisible. Value =! menuVisible.value; }; return { toggleMenu }; }}; </script>Copy the code
provide / inject
- Use the provide tag in the parent component that variable can be accessed by all descendants, no matter how many layers
- Use Inject to access variables in child components