【问题标题】:How to load a local JavaScript file only within certain components如何仅在某些组件中加载本地 JavaScript 文件
【发布时间】:2019-05-28 22:05:42
【问题描述】:

我有一个 JavaScript 文件,一旦安装,我只想包含在一个组件中。例如,这个 JavaScript 文件(称为dashboard.js)应该只在 Dashboard.vue 组件处于活动状态并挂载时运行。

我尝试将代码粘贴到mounted() 中,但这不起作用,因为代码依赖this 作为窗口,而不是Vue 实例。我也尝试将脚本附加到 mount 函数中的 document.head 中,但这似乎是一个大技巧,我知道必须有更好的方法来做到这一点。

//Dashboard.vue
<template>
<div>
Dashboard content here
</div>
</template>
<script>
export default {
    mounted() {
      //code that relies on this being the window object here (jQuery stuff)
    }
}
</script>


//dashboard.js
$(function() {
  $div = $('div');
  $div.on('click', function() {
    //do stuff
  });
});

我希望这个dashboard.js 本地脚本仅在我的组件被挂载时加载和调用。

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    您可以在组件中导入该脚本:

    // Dashboard.vue
    import * as dashboard from "./dashboard";
    

    然后在dashboard.js中导入jQuery

    // dashboard.js
    import jQuery from "jquery";
    window.$ = window.jQuery = jQuery;
    
    $(function() {
      var $div = $("div");
      $div.on("click", function() {
        //do stuff
        alert();
      });
    });
    

    【讨论】:

    • 我同意你的观点,我只是展示了可能的例子。不建议在 vue.js 组件之外进行任何 dom 操作。
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2013-04-06
    • 2016-09-27
    相关资源
    最近更新 更多