如何在Vue3中存取js檔案中的Vue實例?
P粉609866533
P粉609866533 2024-01-21 16:04:50
0
2
787

在 Vue2 中,我能夠存取我的 Vue 實例以使用在 Vue 中註冊的元件。

測試.js

import Vue from 'vue'

   export function renderLogin () {
     Vue.toasted.show('Please login again', { type: 'error', duration: 2000 })
   }

在上面的程式碼中,我能夠存取 toasted 包,因為我已經在 main.js 中使用 Vue 註冊了它。但是,在 Vue3 中,我無法使用 toasted 包,因為我無法存取 js 檔案內的 Vue 實例。

需要有關如何存取 js 檔案內的 Vue 實例('this')的協助。

P粉609866533
P粉609866533

全部回覆(2)
P粉539055526

// Vue 3 組合 API

    sssccc

這與 Vue2 中的方式不完全一樣,但這可能會暴露您正在尋找的內容。


如果你想讓一個套件在 Vue3 中全域可用,你可能需要將以下程式碼加入外掛程式:

    //* This will help for accessing the toasted instance in other files (plugins)
    app.config.globalProperties.$toasted = toasted;

    //* This will expose the toasted instance in components with this.$toasted
    app.provide('$toasted', toasted);

這樣,您就可以在選項 api 中使用下列指令取得 toasted 實例: this.$toasted

使用組合 API: const { $toasted } = _instance.appContext.app.config.globalProperties;

在另一個外掛程式中: constructor(app) { app.config.globalProperties; }

P粉011684326

經過一天的搜索,我能夠從 js 檔案內的 vue 實例存取 toasted 元件。

首先,我們必須匯出應用程式實例才能在 js 檔案中讀取它

main.js

export const app = createApp({
   render() {
     return h(AppWrapper);
   },
});

接下來,我們必須在應用程式實例的 globalProperties 中註冊我們的元件。

app.config.globalProperties.$toast = toast;

我們現在可以在 js 檔案中匯入應用程式實例並存取 toast 元件

測試.js

import { app } from '@/main.js'

app.config.globalProperties.$toast('Toast working fine', {
    type: 'success',
    duration: 2000,
  })

希望這可以幫助別人。如果有其他/更好的方法,請告訴我。謝謝

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!