Home > Web Front-end > Vue.js > body text

Where to put the common js code in vue

下次还敢
Release: 2024-05-02 21:15:40
Original
824 people have browsed it

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.

Where to put the common js code in vue

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>
Copy after login

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:

In

public/js/utils.js:

<code class="javascript">export function myGlobalFunc() {
  // ...
}</code>
Copy after login
Then use in the component:

<code class="javascript">// MyComponent.vue
<script>
import { myGlobalFunc } from '@/js/utils'

export default {
  methods: {
    myMethod() {
      myGlobalFunc()
    }
  }
}
</script></code>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!