I try to find a solution to a problem of circular dependency.
In my Vuejs application, I want a function makeUrl(url)
which computes an absolute url of the given parameter by adding the $router.base value at the beginning.
So I put this in my modules routes.js
:
const router = new VueRouter({
base: '/subdirectory',
//...
});
function makeUrl(url){
return router.base + url;
}
export {makeUrl};
export default router;
routes.js
is imported in main.js
, the entry point of my application, where I create my Vue main instance.
In routes.js
I import my page components, which imports all other components.
In some of them, I need to use the makeUrl()
function I defined.
But I can't import routes.js
because it will create a cyclic import.
I can't move my makeUrl()
function in another module because I need the access the Vue-router instance, so I'll have to import routes.js
in this another modules => circular import again.
So, I heard of $router
variable, so I tried to build a utility component which contains a makeUrl()
function :
//util-component.js
'use strict';
import Vue from 'vue/dist/vue';
const UtilComponent = Vue.component('util-component', {
methods: {
makeUrl(url){
return this.$router.base + url;
}
}
});
export default UtilComponent;
And in my personal component :
//my-component.vue
<template>
<img class="logo" :src="util.makeUrl('/assets/img/logo-transp.svg')" alt=""/>
</template>
<script>
import util from 'utils/util-component';
export default {
data () { return {};}
}
</script>
But with this it end with the same TypeError: e.makeUrl is not a function
... :(
How can I deal with it ? Thanks for your help !