【问题标题】:How to add script to Vue component?如何将脚本添加到 Vue 组件?
【发布时间】:2021-09-04 12:39:33
【问题描述】:

我有 html 模板,其中包含 src 到 js 脚本。 如何将它们添加到 vue 组件中?

<script type='text/javascript' src='js/library/jquery.min.js'></script>
        <!-- Main Js Plugin -->
<script type='text/javascript' src='js/main.min.js'></script>
        <!-- Theme main js -->
<script type='text/javascript' src='./src/assets/js/custom.theme.js'></script

【问题讨论】:

标签: javascript html vue.js


【解决方案1】:

对于 Vue 3:如果脚本将在组件挂载时调用,请在 setup() 函数中添加脚本,这与 Vue 2 的 created 钩子相同。

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'ExampleComponent',
  components: {},
  props: {},
  setup() {
    const googleSignInScript = document.createElement('script');
      googleSignInScript.setAttribute(
        'src',
        'https://accounts.google.com/gsi/client'
      );
      googleSignInScript.setAttribute('async', 'true');
      googleSignInScript.setAttribute('defer', 'true');
      document.head.appendChild(googleSignInScript);

    return {};
  },
});
</script>

如果脚本将在以后使用,您可以将其添加到 onMounted 钩子中

<script lang="ts">
import { defineComponent, onMounted } from 'vue';

export default defineComponent({
  name: 'ExampleComponent',
  components: {},
  props: {},
  setup() {
    onMounted(() => {
      const googleSignInScript = document.createElement('script');
      googleSignInScript.setAttribute(
        'src',
        'https://accounts.google.com/gsi/client'
      );
      googleSignInScript.setAttribute('async', 'true');
      googleSignInScript.setAttribute('defer', 'true');
      document.head.appendChild(googleSignInScript);
    })
    return {};
  },
});
</script>

对于 Vue 2:在 createdmounted 挂钩中添加适合您的应用程序的脚本。

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2018-01-15
    • 2021-11-11
    • 2021-10-25
    • 2020-06-05
    相关资源
    最近更新 更多