简体   繁体   中英

How can i use global functions in Vue?

I have a date formatting function. Now I need to use this method in different components. What's the best practice for this situation? Directive? Filters? Or something different? How can I define this?

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

Module

Assuming you're using Vue CLI or an equivalent bundler, the way that is most composable would be to create a module for utility functions like:

utilities.js

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

Then you could import that function wherever you need it:

SomeComponent.vue

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

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

Edit: You could also make it a method to use it directly from the template:

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

Vue.prototype

Another option is to set the function on Vue.prototype prior to instantiating your app:

main.js

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

new Vue({
...
})

Then the function can be used in any component like:

SomeComponent.vue

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM