【发布时间】: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