我有一个在整个应用程序中使用的函数。我想将这个函数导出到一个模块中,并在需要的地方导入。
组件内部的函数:
navigate: debounce(function() {
this.$router.push({
path: '/cars',
query: this.params
})
}, 200)如何将此函数导出到模块并在组件上使用?
发布于 2019-11-15 01:53:37
可以将函数添加到mixin (https://vuejs.org/v2/guide/mixins.html)中
funcs.js:
export default
{
methods:
{
navigate()
{
debounce(() =>
{
this.$router.push({
path: '/cars',
query: this.params
});
}, 200);
}
}
}component.vue:
import funcs from './funcs.js'
export default
{
...
mixins: [funcs],
...
}发布于 2019-11-15 02:05:34
考虑到您提到的在应用程序中经常使用的方法,您可以向Vue路由器实例添加一个新方法。
const router = new VueRouter({
routes
})
// Create and export a pass-through API so you can use it just like router.push
export const debouncedPush = debounce(router.push, 200);
// Add debouncedPush method on the router
router.debouncedPush = debouncedPush
const app = new Vue({
router
}).$mount('#app') 然后,在组件代码中,您可以像这样使用它
this.$router.debouncedPush({path: '/cars', query: this.params})或者,您可以只导入如下方法:
import { debouncedPush } from './path/to/file'
debouncedPush({path: '/cars'})https://stackoverflow.com/questions/58862639
复制相似问题