第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Vue Composition API:是否有更好的方法在消耗性文件中調(diào)用“emit”?

Vue Composition API:是否有更好的方法在消耗性文件中調(diào)用“emit”?

SMILET 2023-07-20 14:35:48
emit在分離的邏輯文件中訪問的正確方法(或更好的方法)是什么?這就是我目前所做的有效的:foo.jsexport default (emit) => {    const foo = () => { emit('bar') };    return { foo };}然后在消費(fèi)組件上:import { defineComponent } from '@vue/composition-api';import foo from './foo';export default defineComponent({  setup(props, { emit }) {    const { foo } = foo(emit);    return { foo };  }});但我想知道是否有更合適的方法來做到這一點(diǎn)?emit或者在消耗性文件中調(diào)用是一種不好的做法嗎?
查看完整描述

1 回答

?
慕萊塢森

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊

您可能已經(jīng)找到了解決方案,但如果您嘗試類似的方式(正如問題中最初提出的那樣),有一個(gè)稱為getCurrentInstance發(fā)射器的選項(xiàng)(用于 Composition API 的 Vue 2 插件也有一個(gè))。

import { getCurrentInstance } from 'vue';


export default () => {

? const { emit } = getCurrentInstance();


? const foo = () => {

? ? emit('bar');

? };


? return { foo };

}

但請記住,這僅適用于調(diào)用具有SetupContext.

編輯

上述解決方案適用于 Vue 3,但對于早期版本的 Vue +?Composition API 插件,有一點(diǎn)細(xì)微的差別:與其余的Instance Properties一樣,您必須在其前面加上前綴$to be?$emit。(下面的示例現(xiàn)在假定 Typescript 作為目標(biāo)語言,如評論中所述)。

import { getCurrentInstance } from '@vue/composition-api';


export default () => {

? // Ugly workaround, since the plugin did not have the `ComponentInstance` type exported.?

? // You could use `any` here, but that would defeat the purpose of having type-safety, won't it?

? // And we're marking it as `NonNullable` as the consuming components?

? // will most likely be (unless desired otherwise).

? const { $emit, ...context } = getCurrentInstance() as NonNullable<ReturnType<typeof getCurrentInstance>>;


? const foo = () => {

? ? $emit.call(context, 'bar');

? };


? return { foo };

}

然而,對于 Vue 3 的 Composition API,他們確實(shí)ComponentInternalInstance導(dǎo)出了這個(gè)接口。

PS 最好堅(jiān)持將實(shí)例分配給變量的老式方法,然后執(zhí)行context.$emitorvm.$emit而不是必須顯式指定所有內(nèi)容的上下文。我最初提出這個(gè)想法時(shí)沒有意識到這些實(shí)例屬性可能是供內(nèi)部使用的,而下一個(gè) Composition API 的情況并不完全如此。


查看完整回答
反對 回復(fù) 2023-07-20
  • 1 回答
  • 0 關(guān)注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號