【问题标题】:Why is the script run twice?为什么脚本运行两次?
【发布时间】:2021-03-13 05:33:39
【问题描述】:

这是一个最小的例子:https://jsfiddle.net/kxbufL80/

<main>
    <script type="application/javascript">console.log("Why twice?")</script>
</main>

以及如何防止这种情况发生?

【问题讨论】:

  • 不要将脚本注入到将挂载 Vue 实例的 DOM 中。

标签: vue.js


【解决方案1】:

包含&lt;main&gt; 和您的自定义&lt;script&gt; 的标记在加载页面时立即执行(甚至在Vue 运行之前),然后在Vue 挂载到&lt;main&gt; 时再次执行。

假设您无法将&lt;script&gt; 标记移到&lt;main&gt; 之外,解决方法是删除beforeCreate 挂钩中的&lt;script&gt;

new Vue({
  el: "main",
  beforeCreate() {
    document.querySelector('main script').remove()
  }
})

updated fiddle

然而,Vue 模板不应包含 &lt;script&gt; 开头的标签,并且开发版本应在浏览器控制台中警告您这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多