You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 2组件中如何加载外部.js文件?求实现方案

How to Import general.js into Your Vue 2 posts.vue Component

Hey there! No worries at all—let's walk through how to import your general.js file into the posts.vue component. It's pretty simple once you know the right import path and export setup. Here's what you need to do:

First: Make Sure general.js is Properly Exported

Before importing, double-check that your general.js file has a valid export so Vue can access its contents. There are two common export styles:

Default Export (for a single main object/function)

If your general.js holds a collection of utilities as one object, use a default export:

// general.js
export default {
  greet() {
    return "Hello from general.js!";
  },
  appVersion: "1.0.0"
};

Named Exports (for multiple standalone items)

If you want to export individual functions/variables separately:

// general.js
export const greet = () => "Hello from general.js!";
export const appVersion = "1.0.0";

Second: Import general.js into posts.vue

Now, add the import line to your posts.vue script section. The path depends on where general.js is located relative to posts.vue:

Case 1: Same Directory as posts.vue

If general.js is in the same folder as posts.vue:

<template> 
<div> 
<p> {{message}} </p> 
<p> {{greeting}} </p>
</div> 
</template> 

<script> 
import axios from 'axios'; 
import _ from 'lodash'; 
import general from './general.js'; // Default import
// OR for named exports: import { greet, appVersion } from './general.js';

export default { 
data() { 
return { 
message : 'Here is my HTML',
greeting: general.greet() // Using the imported utility
// OR greeting: greet() if using named exports
} 
} 
} 
</script>

Case 2: In a Subdirectory (e.g., src/utils/general.js)

Use the @ alias (which points to your project's src folder in Vue 2) for cleaner paths:

import general from '@/utils/general.js';
// OR import { greet } from '@/utils/general.js';

Case 3: Global Access (If You Need It Everywhere)

If you want to use general.js utilities across all components without importing each time, register it on Vue's prototype in main.js:

// main.js
import Vue from 'vue';
import general from './path/to/general.js';

Vue.prototype.$general = general;

Then use it in posts.vue like this:

export default { 
data() { 
return { 
message : 'Here is my HTML',
greeting: this.$general.greet()
} 
} 
}

That's it! Just match the import style to how you exported from general.js, and you'll be all set.

内容的提问来源于stack exchange,提问作者Parth Jasani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:14:14