'How to separate script section of Vue file to another file?

A vue file in my project has become too big. I wanted to seperate its script section into a js file. In js file, I export the Vue object;

export default new Vue({
  data: {
    search: "",
    ...

And import it in the Vue file;

<script src="./RecordNameTable.js">
</script>

But this is not working, it gives errors. I can import it as a .vue file which has the classic Vue syntax between <script></script> tags. But I do not want this. How to solve this problem?



Solution 1:[1]

You have to export an object from your external script, Not a Vue instance.

Here is a simple solution

App.vue

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

// This will work
<script src="./app.js"></script>

// this will work too
<script>
    import App from './app.js';

    export default App;
</script>

app.js

export default {
    data(){
        return {
            message: "Hello world"
        };
    }
}

Solution 2:[2]

You solve the problem by dropping the "But I do not want this." attitude and simply use the only available solution at this point:

<script>
    import Obj from 'location';

    export default Obj;
</script>

Solution 3:[3]

If it's become too big the correct approach is to break your template down into further components, not simply move the problem (and making it worse) by moving the script section to another file. You're approaching this wrong.

Solution 4:[4]

For vue 3 using Object Destructuring

<script>
import File_script from "./file_script.js";

export default {...File_script}
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mjh
Solution 3 user9993
Solution 4 user9851053