Home  >  Article  >  Web Front-end  >  Where to put the js code written in vue

Where to put the js code written in vue

下次还敢
下次还敢Original
2024-05-02 22:18:55706browse

JavaScript code is usually placed in the <script> tag in Vue.js, or it can be placed in an external JavaScript file or .vue file. Vue 3 and above supports placing JavaScript logic in the setup() function. Other placement locations include mixins, plugins, and global installations.

Where to put the js code written in vue

Location of JavaScript code in Vue.js

In Vue.js, JavaScript code is usually placed below Location:

1. <script> Tag

This is the most common way to place JavaScript code in a component. The <script> tag should be placed after the <template> tag, as shown below:

<code class="html"><template>
  <!-- HTML 模板 -->
</template>

<script>
  export default {
    // 组件选项
    data() {
      return {
        // 数据
      }
    },
    methods: {
      // 方法
    }
  }
</script></code>

2. External JavaScript files

For larger or complex components, it may be more convenient to place the JavaScript code in a separate external file. External files can be imported into the <script> tag using the src attribute, as shown below:

<code class="html"><script src="./my-component.js"></script></code>

3. .vue Files

Single-file components (.vue files) in Vue.js combine HTML, CSS, and JavaScript code in a single file. JavaScript code sections can be written as in <script> tags.

4. setup() Function

In Vue 3 and above, the JavaScript logic of the component can be placed setup() function. setup() The function returns a reactive object containing component options.

<code class="javascript">const MyComponent = {
  setup() {
    const count = ref(0)
    const increment = () => count.value++

    return { count, increment }
  }
}</code>

5. Other locations

In some cases, you may need to place the JavaScript code in other locations, such as:

  • mixins: Used to share code between multiple components.
  • plugins: Used to add custom functionality to Vue instances.
  • Global installation: Used to use code in all components.

The above is the detailed content of Where to put the js code written in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:How to use v-html in vueNext article:How to use v-html in vue