iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0
Vue.js

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

Vue.js 新手入門之路 - inject

  • 分享至 

  • xImage
  •  

一般狀況下,我們若想傳遞 data 會使用 props,若接收元件是在深層的狀況,且該元件之父級元件並不 care 該 props ,我們便可以利用 provide / inject 來跨層級傳遞,因為有點抽象這邊直接使用官方文件的圖
https://ithelp.ithome.com.tw/upload/images/20250915/20178296KChn9Uz4pj.png

改為直接傳到所需要的元件
https://ithelp.ithome.com.tw/upload/images/20250915/20178296T0NEGuEZ5j.png

eg.
子元件:

<script setup>
import { inject } from 'vue'
const theme = inject('theme', null)
</script>

<template>
  <p>Current theme: {{ theme?.value }}</p>
</template>

父元件:

<script setup>
import { ref, provide } from 'vue'
const theme = ref('light')
provide('theme', theme)
</script>

<template>
  <div class="box">
    <button @click="theme.value = theme.value === 'light' ? 'dark' : 'light'">{{theme}}</button>
  </div>
  
</template>

我們也可以在應用層使用 provide 這樣便所有元件都能 inject

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

const api = { get(){ /* ... */ } }
app.provide('api', api)

app.mount('#app')

別名注入

eg.
子元件:

<script>
export default {
  name: 'Child',
  inject: {
    localMessage: { from: 'message' }
  }
}
</script>

<template>
  <p>{{ localMessage }}</p>
</template>

父元件:

<script>
import Child from './components/inject.vue'

export default {
  name: 'Parent',
  components: { Child },
  provide: {
    message: 'Hello from parent'
  }
}
</script>

<template>
  <div class="box">
    <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>

將父元件定義的 message 以別名 localMessage 注入
https://ithelp.ithome.com.tw/upload/images/20250915/20178296Kz14ly8Pqz.png

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


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

尚未有邦友留言

立即登入留言