iT邦幫忙

2025 iThome 鐵人賽

DAY 27
0
Vue.js

Vue.js 新手入門之路系列 第 27

Vue.js 新手入門之路 - inject(二)

  • 分享至 

  • xImage
  •  

預設值注入

通常 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',所以顯示的是子元件定義之預設值
https://ithelp.ithome.com.tw/upload/images/20250916/20178296TTxxz9YsTT.png

搭配響應式的注入

我們需要使用計算屬性
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 後面加上一個 "!"
https://ithelp.ithome.com.tw/upload/images/20250916/20178296puZWlBRRuk.png

ref:
https://zh-hk.vuejs.org/guide/components/provide-inject.html#prop-drilling


上一篇
Vue.js 新手入門之路 - inject
下一篇
Vue.js 新手入門之路 - router
系列文
Vue.js 新手入門之路30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言