S. *_* J. 5 javascript mixins vue.js vue-router vue-mixin
我想为每个路线动态设置窗口的标题,因此在每个routes: []子对象中都有一个meta: { title: ... }对象。例如:
routes: [
{
path: 'profile/:id',
name: 'Profile',
component: Profile,
meta: {
title: function (to, cb) {
const profileId = parseInt(to.params.id);
// ... do stuff ...
}
}
}
]
Run Code Online (Sandbox Code Playgroud)
我称呼这个标题函数afterEach:
router.afterEach((to) => {
document.title = 'My Site';
if (to.meta && to.meta.title) {
to.meta.title(router.app, to, (result) => { document.title += ' | ' + result; });
}
});
Run Code Online (Sandbox Code Playgroud)
在... do stuff ...部分我想打电话从我的混入的方法GetAndStore.js叫loadProfile(profileId)。我已添加GetAndStore到路由器的mixins中,但loadProfile不可用(this.loadProfile未定义)。我GetAndStore在全球范围内加载,并再次尝试了相同的结果。在过去的一个小时中,我尝试了所有可以想到的配置,但GetAndStore从此设置中根本找不到任何方法来访问方法。
为了从内部访问mixin方法,我缺少什么或需要重组什么的任何想法routes->element->meta->title?
问题是...
Mixins 是一种为Vue 组件分发可重用功能的灵活方式
Vue-router 不是组件,您也无权访问为路由加载的组件。
我的建议是loadProfile从你的GetAndStoremixin 中进行命名导出。假设你的 mixin 是这样导出的
import axios from 'axios' // just an example
export default {
methods: {
loadProfile (profileId) {
return axios.get(...)
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将您的函数移出默认导出并将其命名...
export function loadProfile (profileId) {
return axios.get(...)
}
export default {
methods: {
loadProfile
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以只导入loadProfile路由定义中的函数...
import { loadProfile } from 'GetAndStore'
Run Code Online (Sandbox Code Playgroud)
当然,您也可以按原样导入 mixin 并使用
import GetAndStore from 'GetAndStore'
// snip
GetAndStore.methods.loadProfile(to.params.id).then(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1274 次 |
| 最近记录: |