通常 inject
是由父層 provide
,若無則 Vue 會拋出一個 warning,此時可以在子元件定義預設的 inject
值,就算父元件沒有提供也不會報錯
eg.
子元件
<script setup>
import { inject } from 'vue'
const msg = inject('message', 'default value')
// 物件型別 使用工廠:第三個參數 true 表示把函式當工廠執行
const user = inject('user', () => ({ name: 'no user provide' }), true)
</script>
<template>
<div>
<p>message:{{ msg }}</p>
<p>user.name:{{ user.name }}</p>
</div>
</template>
父元件
<script>
import Child from './components/inject.vue'
export default {
name: 'Parent',
components: { Child },
provide:{
message:'father'
}
}
</script>
<template>
<div class="box">
<Child/>
</div>
</template>
父層有 provide 'message' 所以顯示 father,但沒有 provide 'user.name',所以顯示的是子元件定義之預設值
我們需要使用計算屬性
eg.
父元件
<script setup>
import { ref, computed, provide } from 'vue'
import Child from './components/inject.vue'
let message = ref('hello!')
provide('message', computed(() => message.value))
</script>
<template>
<div class="box">
<button @click="message = message + '!'">append "!"</button>
<Child/>
</div>
</template>
<style scoped>
.box{
display: flex;
gap:3px;
text-align: center;
justify-content: center;
flex-direction: column;
font-size: x-large;
margin-left: 450px;
margin-top: 5px;
padding: 35px;
}
</style>
子元件
<script setup>
import { inject } from 'vue'
const msg = inject('message', 'default value')
</script>
<template>
<p>from parent:{{ msg }}</p>
</template>
每按一次按鈕畫面會響應並在 hello 後面加上一個 "!"
ref:
https://zh-hk.vuejs.org/guide/components/provide-inject.html#prop-drilling