Home > Article > Web Front-end > Where to put the common js code in vue
There are two places to store public JS code in Vue: main.js file: used to initialize Vue instances and set global configurations to ensure that public code is accessible in all components. JS files in the public/ directory: can be loaded into the page via CDN or server.
The location where public JS code is stored in Vue
In Vue.js, public JS code is usually stored The code is placed in the following two locations:
1. main.js
file
main.js
The file is Vue The entry file of the project is mainly used to initialize the Vue instance and set global configuration. Placing common JS code here ensures that it is accessible in all components.
Example:
<code class="javascript">// main.js import Vue from 'vue' import MyGlobalFunc from './utils/myGlobalFunc' Vue.component('my-component', { // ... }) Vue.mixin({ methods: { myGlobalFunc() { return MyGlobalFunc() } } })</code>
2. public/
JS files in the directory
## The #public/ directory is used to store static resources such as CSS, JS, and images. Placing common JS code here allows them to be loaded directly into the page via a CDN or server.
Example:
Inpublic/js/utils.js:
<code class="javascript">export function myGlobalFunc() { // ... }</code>Then use in the component:
<code class="javascript">// MyComponent.vue <script> import { myGlobalFunc } from '@/js/utils' export default { methods: { myMethod() { myGlobalFunc() } } } </script></code>
The above is the detailed content of Where to put the common js code in vue. For more information, please follow other related articles on the PHP Chinese website!