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

Hor*_*rus 6 javascript global function vue.js vue-component

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

dateWithoutTime(date) {
  return date ? date.split("T")[0] : ""
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 11

模块

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

实用程序.js

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

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

一些组件.vue

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

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

编辑:您还可以将其设为直接从模板使用它的方法:

methods: {
  dateWithoutTime      // Same as `dateWithoutTime: dateWithoutTime`
}
Run Code Online (Sandbox Code Playgroud)

Vue.原型

Vue.prototype另一种选择是在实例化您的应用程序之前设置该功能:

main.js

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

new Vue({
...
})
Run Code Online (Sandbox Code Playgroud)

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

一些组件.vue

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