我有一个日期格式化函数,现在需要在不同的组件中使用这个方法。在这种情况下,最佳实践是什么?指令?过滤器?还是其他什么东西?我该如何定义它?
dateWithoutTime(date) {
return date ? date.split("T")[0] : ""
}
我有一个日期格式化函数,现在需要在不同的组件中使用这个方法。在这种情况下,最佳实践是什么?指令?过滤器?还是其他什么东西?我该如何定义它?
dateWithoutTime(date) {
return date ? date.split("T")[0] : ""
}
假设您正在使用Vue CLI或等效的打包程序,最具可组合性的方式是创建一个用于实用函数的模块,例如:
utilities.js
export const dateWithoutTime = function(date) {
return date ? date.split("T")[0] : ""
}
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
上:
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);
}
}
}