簡體   English   中英

在 Vue.js 應用程序中動態加載 JavaScript 腳本

[英]Loading a JavaScript script dynamically in a Vue.js app

如何在 Vue.js 應用程序中動態加載 JavaScript 腳本?

這是一個天真的解決方案:

    <script async v-bind:src="srcUrl"></script>
    <!--<script async src="https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37"></script>-->

但是第一行不會加載腳本(它不會將script元素添加到 HTML)。

第二行有效。 第二行是相同的,只是 app 變量被替換為純文本( srcUrl => https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37 )。

我的錯在哪里?

完整的演示供參考(它應該在空白頁面上加載谷歌自定義搜索引擎):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="load-script">
    <div>{{ srcUrl }}</div>
    <div class="gcse-searchbox"></div>
    <div class="gcse-searchresults"></div>
    <script async v-bind:src="srcUrl"></script>
    <!--<script async src="https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37"></script>-->
</div>
<script>
    new Vue({
        el: '#load-script',
        data: {
            srcUrl: "https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37"
        }
    });
</script>
</body>
</html>

我發現了相關的問題,但它們似乎並沒有准確地描述這種情況:

您可以隨時將<script>元素動態添加到 DOM。

如果您使用的是 Vue,則可以在頁面加載時使用其mounted屬性將腳本添加到load-script div:

Vue({
  mounted: function () {
    let divScripts = document.getElementById('load-script');
    let newScript = document.createElement('script');
    newScript.src = 'https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37';
    divScripts.appendChild(newScript);
  }
});

替代方法 - 使用 LoadScript

作為將 function 添加到已mounted的 Vue 屬性的替代方法,有一個名為LoadScript的簡單 Vue 插件可以加載和卸載腳本。

import LoadScript from 'vue-plugin-load-script';
Vue.use(LoadScript);

要加載腳本:

Vue.loadScript('https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37')
  .then(() => {
    // do something after script loads
  })
  .catch(() => {
    // do something if load fails
  });

卸載腳本:

Vue.unloadScript('https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37')
  .then(() => {
    // do something after script unloads
  })
  .catch(() => {
    // do something if unload fails
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM