Heim  >  Fragen und Antworten  >  Hauptteil

Wie greife ich in Vue3 auf die Vue-Instanz in der JS-Datei zu?

In Vue2 kann ich auf meine Vue-Instanz zugreifen, um in Vue registrierte Komponenten zu verwenden.

test.js

import Vue from 'vue'

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

Im obigen Code kann ich auf das geröstete Paket zugreifen, weil ich es mit Vue in main.js registriert habe. In Vue3 kann ich das geröstete Paket jedoch nicht verwenden, da ich nicht auf die Vue-Instanz in der js-Datei zugreifen kann.

Benötigen Sie Hilfe beim Zugriff auf die Vue-Instanz („this“) in einer js-Datei.

P粉609866533P粉609866533271 Tage vor792

Antworte allen(2)Ich werde antworten

  • P粉539055526

    P粉5390555262024-01-22 11:32:17

    // Vue 3 组合 API

        
    

    这与 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; }

    Antwort
    0
  • P粉011684326

    P粉0116843262024-01-22 11:16:44

    经过一天的搜索,我能够从 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,
      })

    希望这可以帮助别人。如果有其他/更好的方法,请告诉我。谢谢

    Antwort
    0
  • StornierenAntwort