Vue: sharing methods in a js file

Viewed 41

i'm working on a multipage website in vue and often need the same methods for different views. I read that you can do that with a shared .js file and it works if i have my "test method" downloadModel as a single function but as soon as i try to split it up, i get a TypeError: Cannot read properties of undefined (). How can i fix this? Sry i'm relatively new in this world. :)

export default {
methods:{  
    downloadModel(id) {
        this.printMessage('Download',id)
    },

    printMessage(string,id){
        console.log(string, id)
    },

} }

2 Answers

Try something like this :

In you share.js file :

function downloadModel(id) {
    this.printMessage('Download',id)
}

function printMessage(string,id) {
    console.log(string, id)
}

export { downloadModel, printMessage };

In your page.js file (for exemple)

import { downloadModel, printMessage } from 'js/shared.js';

Note that you don't need to export / import printMessage if this function is only call by downloadModel and you don't need to use it by yourself in page.js

You can use mixins to achieve what you want here. If several components use the same function, you can put that in a mixin and that mixin in as many components as you like.

Example:

Mixin
// mixins/shared.vue
export default {
    methods: {
        sharedFunction() {
            console.log("Hi, i'm a shared function!");
        }
    }
}
Component 1
// components/comp1.vue
import SharedFunctionMixin from '../mixins/shared.vue';

export default {
    mixins: [SharedFunctionMixin],
    
    mounted() {
        this.sharedFunction();
    }
}
Component 2
// components/comp2.vue
import SharedFunctionMixin from '../mixins/shared.vue';

export default {
    mixins: [SharedFunctionMixin],
    
    mounted() {
        this.sharedFunction();
    }
}
Related