我该如何在Vue中使用全局函数?

6

我有一个日期格式化函数,现在需要在不同的组件中使用这个方法。在这种情况下,最佳实践是什么?指令?过滤器?还是其他什么东西?我该如何定义它?

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

1
创建一个 mixin 并将函数(方法)放在其中,然后只需在需要该函数的地方包含 mixin 即可。 - Vucko
请注意,混入是一种反模式,并在Vue 3中被淘汰,最好不要使用。 - Dan
1个回答

10

模块

假设您正在使用Vue CLI或等效的打包程序,最具可组合性的方式是创建一个用于实用函数的模块,例如:

utilities.js

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

然后你可以在需要的任何地方导入该函数:
某个组件.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);
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接