Normally I would create a util.js file in /assets/js, it will look like:
const util = {
myFunction1 () {
// Do something
},
myFunction2 () {
// Do something
}
}
export default util
then import it in any vue file that need these functions, like:
<script>
import util from '~/assets/js/util'
export default {
methods: {
myFunction3 () {
util.myFunction1()
}
}
}
</script>
if you don't want to import it manually in every vue file, then use a global mixin, https://vuejs.org/v2/guide/mixins.html#Global-Mixin, like this:
1, create a js file in the plugins folder (I normally just name it main.js)
2, then in main.js:
import Vue from 'vue'
import util from '~/assets/js/util'
Vue.mixin({
methods: {
myFunction3 () {
util.myFunction1()
}
}
})
3, add main.js in nuxt.config.js:
module.exports = {
...
plugins: ['~/plugins/main.js']
...
}
Thanks!! @HoraceKeung very helpful
Recently I did the same thing. I created a lib folder and placed all common type of function is separate file based of category (common.js, loginHelper.js etc) and just imported in a component or in mixins and then called it as you said.
However, I am not sure, if we can do this then my mixins come into existence.
what is the uses difference between normal js file and mixins way?
in mixing I found a strange issue but not in lib file..
I am still not able to understand the reason.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Normally I would create a util.js file in /assets/js, it will look like:
then import it in any vue file that need these functions, like:
if you don't want to import it manually in every vue file, then use a global mixin, https://vuejs.org/v2/guide/mixins.html#Global-Mixin, like this:
1, create a js file in the plugins folder (I normally just name it main.js)
2, then in main.js:
3, add main.js in nuxt.config.js: