【问题标题】:Vuejs helper with route带有路由的 Vuejs 助手
【发布时间】:2020-03-10 18:11:07
【问题描述】:

我有一个在整个应用程序中都使用的功能。 我想将此函数导出到模块并在需要的地方导入。

组件内的函数:

navigate: debounce(function() {
  this.$router.push({
    path: '/cars',
    query: this.params
  })
}, 200)

如何将此功能导出到模块并在组件上使用?

【问题讨论】:

标签: vue.js


【解决方案1】:

您可以将函数添加到 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],
  ...
}

【讨论】:

    【解决方案2】:

    考虑到您提到它在您的应用程序中经常使用,您可以向您的 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'})
    

    【讨论】:

    • 有没有办法让 debouncedPush 和 router.push 同时工作?
    • 添加debouncedPush 不会以任何方式影响router.push。您可以单独使用两者。 (我假设您正在使用的 debounced 实现创建了一个新的包装函数并返回它(不会弄乱底层函数))
    猜你喜欢
    • 2016-05-22
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 2021-11-09
    相关资源
    最近更新 更多