Vuerouter:需要导入,但是如何避免循环依赖?

Tha*_*ric 5 circular-dependency vue.js vue-router

我试图找到解决循环依赖问题的方法。在我的 Vuejs 应用程序中,我想要一个makeUrl(url)通过在开头添加 $router.base 值来计算给定参数的绝对 url 的函数。

所以我把它放在我的模块中routes.js

const router = new VueRouter({
    base: '/subdirectory',
    //...
});

function makeUrl(url){
    return router.base + url;
}

export {makeUrl};
export default router;
Run Code Online (Sandbox Code Playgroud)

routes.js导入到main.js我的应用程序的入口点,我在其中创建 Vue 主实例。

routes.js我导入我的页面组件中,它导入了所有其他组件。在其中一些中,我需要使用makeUrl()我定义的函数。但我无法导入,routes.js因为它会创建循环导入。

我无法makeUrl()在另一个模块中移动我的函数,因为我需要访问 Vue-router 实例,所以我必须routes.js再次导入另一个模块 => 循环导入。

所以,我听说了$router变量,所以我尝试构建一个包含makeUrl()函数的实用程序组件:

//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;
Run Code Online (Sandbox Code Playgroud)

在我个人的部分:

//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>
Run Code Online (Sandbox Code Playgroud)

但这样它就以同样的结果结束了TypeError: e.makeUrl is not a function......:(

我该如何处理?感谢您的帮助 !

tha*_*ksd 3

对于你的实用函数,你应该使用mixin来代替:

// mixins/Utils.js
export default {
  methods: {
    makeUrl(url) {
      return this.$router.options.base + url;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以将 mixin 添加到您的组件中,如下所示:

<script>
import Utils from 'mixins/Utils';

export default {
  mixins: [ Utils ],
}
</script>
Run Code Online (Sandbox Code Playgroud)

现在,您的组件有一个makeUrl将在其范围内调用的方法,这意味着它的引用将this.$routerVueRouter您想要的实例。

您可以像任何其他组件方法一样在模板中使用此方法:

<template>
  <img class="logo" :src="makeUrl('/assets/img/logo-transp.svg')" alt=""/>        
</template>
Run Code Online (Sandbox Code Playgroud)