简体   繁体   中英

How to send a message from index.html to Vue.js 3 instance?

So, imagine Vue index.html that also loads some custom script:

<!DOCTYPE html>
<html lang="en">
<head>
    ...
    ...
    <script type="text/javascript">
    languagePluginLoader.then(function () {
        pyodide.loadPackage("someName").then(() => {
            // Send message to Vue that everything is fine
        }).catch((err) => {
            // Send message to Vue that it failed
        })
    })
    </script>
    ...
    ...
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

Is there a way to communicate with running Vue instance or/and Vuex from the index.html file? For example, I want to show "Loading..." until the script is fully loaded, etc.

  • One way will be to send the message to the service worker and then from the service worker to Vue, but it feels unpractical.

  • Another way is to set windows.script_status = true after the initialization, but window object is not reactive, so Vue will check it once, get undefined and forget about it.

  • UPD: Third way will be to inject scripts from the Vue side and put some function into script.onload to get when it's ready, but not sure how stable the solution is.

So, any advice will do:)

也许我误解了,但是如果我使用 Vue,我喜欢使用 vuex,当我这样做时,我总是将我的 API 访问功能放入我的 vuex 商店中的操作中,这些操作会触发突变,从而更新您可以使用的状态然后观察/反应。

I would go the route of an external event hub. Since Vue 3 removed the $on, $off and $once instance methods, the official migration strategy for an event hub is to use an external library, such as mitt . Using eg mitt you should be able to signal Vue easily once your other custom scripts have been loaded.

The solution was the third one - inject script manually through mounted and put all the logic into script.onload part. Google Maps example:

mounted: function () {
    if (window.google && window.google.maps) {
        this.create_map();
        return;
    }

    var self = this;
    var script = document.createElement("script");
    script.onload = function () {
        if (!window.google && !window.google.maps)
            return void (console.error("no google maps script included"));

        self.create_map();
    };

    script.async = true;
    script.defer = true;
    script.src = "https://maps.googleapis.com/maps/api/js?key=googleapikeyxxxx&callback=initMap";
    document.getElementsByTagName("head")[0].appendChild(script);
}

Picked the logic from another SO question's answer : https://stackoverflow.com/a/45605316/1598470 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM