簡體   English   中英

Vue 3 組合 API 和對 Vue 實例的訪問

[英]Vue 3 composition API and access to Vue instance

main.js我有這樣的東西:

import { myUtilFunc} from './helpers';
Object.defineProperty(Vue.prototype, '$myUtilFunc', { value: myUtilFunc });

這樣,我有接取myUtilFunc橫跨整個應用程序與this.$myUtilFunc

但是,如果我無法訪問this如何在 Vue 3 的setup()方法中實現相同的功能?

使用provide / inject

提供

const app = createApp(App);
app.provide('someVarName', someVar);  // `Provide` a variable to all components here

注入

// In *any* component
const { inject } = Vue;
...
setup() {
  const someVar = inject('someVarName');   // injecting variable in setup
}

請注意,您不必從應用程序根目錄提供,但也provide從任何組件僅提供其子組件:

// In *any* component
setup() {
  ...
},
provide() {
  return {
    someVarName: someVar
  }
}

原答案

[編輯:雖然我在下面的原始答案對context屬性仍然有用,但不再推薦使用context.root指南中不再提及並且可能很快會被棄用。]

在 Vue 3 中, setup有一個可選的第二個參數context 您可以通過context.root而不是this訪問 Vue 實例:

setup(props, context) {
  context.root.$myUtilFunc  // same as `this.$myUtilFunc` in Vue 2
}

您可以通過context訪問的內容:

context.attrs
context.slots
context.parent
context.root
context.emit

雖然丹的答案是正確的,但我想提供評論中提到的已接受答案的替代方案。 各有優缺點,大家可以根據自己的需求來選擇。

要理解為什么下面的代碼有效,重要的是要記住,提供的屬性在組件樹中是可傳遞的。 inject('foo')將在每個父級中查找'foo',一直到app的層次結構; 無需在中間包裝器中聲明任何內容。

所以,我們可以寫這樣的東西,其中 globalDateFormatter() 只是我們想要在樹下的任何組件中使用的示例函數:

主文件

import { createApp } from 'vue'
import App from './App.vue'

const globalDateFormatter = (date) => {
    return '[' + date.toLocaleString() + ']'
}

const app = createApp(App)
app.provide('globalDateFormatter', globalDateFormatter) // <-- define here
app.mount('#app')

然后,在一些DeepDownComponent.vue 中

<template>
  <p> {{ fmt(new Date()) }} </p>
</template>

<script>
import { inject } from 'vue'
export default {
    setup(){
        const fmt = inject('globalDateFormatter', x => x.toString()) 
        //           ^-- use here, optional 2nd parameter is the default
        return {fmt}
    }
}
</script>

顯然,你可以直接導入和使用provideinject以下簽名

provide<T>(key: InjectionKey<T> | string, value: T): void

inject<T>(key: InjectionKey<T> | string, defaultValue: T): T

代碼中的任何地方,不必是app.provide()

您還可以提供值,甚至是全局存儲,就像這樣,只是不要忘記根據需要使用ref()reactive()

簡而言之,無論何時您更喜歡依賴注入,提供/注入都是您的朋友。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM