【问题标题】:How can I use global functions in Vue?如何在 Vue 中使用全局函数?
【发布时间】:2021-05-15 00:40:51
【问题描述】:

我有一个日期格式化功能。现在我需要在不同的组件中使用这个方法。这种情况的最佳做法是什么?指示?过滤器?还是有什么不同?我该如何定义?

dateWithoutTime(date) {
  return date ? date.split("T")[0] : ""
}

【问题讨论】:

  • 创建一个 mixin 并将函数(方法)放入其中,然后在需要该函数的地方包含 mixin。

标签: javascript function vue.js vue-component global


【解决方案1】:

模块

假设您使用的是 Vue CLI 或等效的捆绑器,最可组合的方式是为实用功能创建一个模块,例如:

utilities.js

export const dateWithoutTime = function(date) {
  return date ? date.split("T")[0] : ""
}

然后你可以在任何你需要的地方导入这个函数:

SomeComponent.vue

import { dateWithoutTime } from '@/modules/utilities.js'

export default {
  data: () => ({
    someDate: new Date()
  }),
  methods: {
    someMethod() {
      return dateWithoutTime(this.someDate);
    }
  }
}

编辑:你也可以让它成为一种直接从模板中使用它的方法:

methods: {
  dateWithoutTime      // Same as `dateWithoutTime: dateWithoutTime`
}

Vue.prototype

另一种选择是在实例化您的应用之前在Vue.prototype 上设置函数:

main.js

Vue.prototype.$dateWithoutTime = function(date) {
  return date ? date.split("T")[0] : ""
}

new Vue({
...
})

那么该函数可以在任何组件中使用,例如:

SomeComponent.vue

export default {
  data: () => ({
    someDate: new Date()
  }),
  methods: {
    someMethod() {
      return this.$dateWithoutTime(this.someDate);
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2020-02-16
    • 2021-09-06
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多