IT이야기

index.html에서 Vue.js 3 인스턴스로 메시지를 보내는 방법

cyworld 2022. 5. 2. 21:27
반응형

index.html에서 Vue.js 3 인스턴스로 메시지를 보내는 방법

그래서, Vue를 상상해보라.index.html일부 사용자 지정 스크립트도 로드:

<!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>

에서 실행 중인 Vue 인스턴스 또는/및 Vuex와 통신할 수 있는 방법이 있는가?index.html파일? 예를 들어 "로드 중...대본이 완전히 로드될 때까지.

  • 한 가지 방법은 서비스 노동자에게 메시지를 보낸 다음 서비스 노동자에게서 부에까지 메시지를 보내는 것이겠지만, 그것은 현실적이지 못한 느낌이다.

  • 또 다른 방법은 설정하는 것이다.windows.script_status = true초기화 후, 그러나window물체가 반응하지 않기 때문에 부에가 한번 확인해서undefined잊어버려

  • UPDATE: 세 번째 방법은 Vue 쪽에서 스크립트를 주입하고 몇 가지 기능을 추가하는 것이다.script.onload준비는 되었지만 해결책이 얼마나 안정적인지는 확실하지 않다.

그러니 어떤 조언이라도:)

나는 외부 이벤트 허브의 길을 갈 것이다.Vue 3에서 $on, $off 및 $one 인스턴스(instance) 방법을 제거했으므로 이벤트 허브의 공식 마이그레이션 전략미트 같은 외부 라이브러리를 사용하는 것이다.예를 들어, 다른 사용자 지정 스크립트가 로드되면 Mit를 사용하여 Vue에 쉽게 신호를 보낼 수 있어야 한다.

해결책은 세 번째 - 주입 스크립트를 통해mounted그리고 모든 논리를 에 집어넣었다.script.onloadpart. Google 지도 예제:

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);
}

다른 SO 질문의 답변에서 논리를 선택했다: https://stackoverflow.com/a/45605316/1598470.

참조URL: https://stackoverflow.com/questions/64544245/how-to-send-a-message-from-index-html-to-vue-js-3-instance

반응형