Vue.js:在 vue.router 路由中使用 mixin 函数

Vue.js: Using mixin functions inside vue.router routes

我想为每条路线动态设置 window 的标题,所以在每个 routes: [] child object 我有一个 meta: { title: ... } object。例如:

routes: [
{
  path: 'profile/:id',
  name: 'Profile',
  component: Profile,
  meta: {
    title: function (to, cb) {
      const profileId = parseInt(to.params.id);
      // ... do stuff ...
    }
  }
}
]

我在 afterEach 钩子中调用这个标题函数:

router.afterEach((to) => {
    document.title = 'My Site';
    if (to.meta && to.meta.title) {
        to.meta.title(router.app, to, (result) => { document.title += ' | ' + result; });
    }
});

... do stuff ... 部分,我想从我的 mixin GetAndStore.js 中调用一个名为 loadProfile(profileId) 的方法。我将 GetAndStore 添加到路由器的 mixins 中,但是 loadProfile 不可用(this.loadProfile 未定义)。我在全局加载 GetAndStore 并再次尝试,结果相同。在过去的一个小时里,我已经尝试了所有我能想到的配置,但我根本没有找到任何方法来从此设置中访问 GetAndStore 中的方法。

关于我遗漏了什么或我需要重组什么以便从 routes->element->meta->title 中访问 mixin 方法的任何想法?

也许您可以尝试在 Profile 组件中的 beforeRouteEnter 上执行此操作。所以你可以在那里获取元标题并设置页面标题,在那里你将可以访问 mixin 方法:

beforeRouteEnter (to, from, next) {
  if (to.meta && to.meta.title) {
    to.meta.title(router.app, to, (result) => { document.title += ' | ' + result; });
  }
},

文档:https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

问题是……

Mixins are a flexible way to distribute reusable functionalities for Vue components

Vue-router 不是组件,您也无权访问为路由加载的组件。

我的建议是从您的 GetAndStore 混入中制作 loadProfile 命名导出。假设你的 mixin 被导出为

import axios from 'axios' // just an example

export default {
  methods: {
    loadProfile (profileId) {
      return axios.get(...)
    }
  }
}

您可以将您的函数移出默认导出并将其命名...

export function loadProfile (profileId) {
  return axios.get(...)
}

export default {
  methods: {
    loadProfile
  }
}

然后您可以在路由定义中只导入 loadProfile 函数...

import { loadProfile } from 'GetAndStore'

当然,你也可以按原样导入mixin,然后使用

import GetAndStore from 'GetAndStore'

// snip

GetAndStore.methods.loadProfile(to.params.id).then(...)