亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

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

1 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

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

import { getCurrentInstance } from 'vue';


export default () => {

? const { emit } = getCurrentInstance();


? const foo = () => {

? ? emit('bar');

? };


? return { foo };

}

但請記住,這僅適用于調用具有SetupContext.

編輯

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

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,他們確實ComponentInternalInstance導出了這個接口。

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


查看完整回答
反對 回復 2023-07-20
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號