How do I define a global method in vue?

The events By Filters method is used as a calculated property for the v-for loop in the component:

getters: {
        eventsByFilters(state) {
            var events = state.events
            if (state.search === '' && state.selected) {
                switch (state.selected) {
                    case 'month':
                        return events.filter(item => this.isMonthEqualNow(item))
                    case 'week':
                        return events.filter(item => this.isMonthEqualNow(item) && this.isWeekEqualNow(item))
                    case 'day':
                        return events.filter(item => this.isMonthEqualNow(item) && this.isWeekEqualNow(item)
                            && this.isDayEqualNow(item))
                    default:
                        return events
                }
            } else {
                return events.filter(item => item.title.indexOf(state.search) !== -1)
            }
        },

I need to use the isMonthEqual and other methods to find out if they belong to certain dates.But I find it difficult to access them:

if I define them in actions, I can't access them, since context is not present in getter;

if I define globally, too, there is no way to access them(this is undefined in this case, and without this, the error that the method is undefined is thrown);

Upvotes: 1

Views: 215

Answers (1)

Daniel Elkington
Daniel Elkington

Reputation: 3637

I'll assume you created your project using the Vue CLI, and are thus using webpack. You should be able to define these methods in a separate file, export them, and then import them into your store files.

/Helpers/GlobalFunctions.js

export function isMonthEqual(param1, param2) {
  // blah blah blah
}

store.js

// Top of the file
import { isMonthEqual } from '@/Helpers/GlobalFunctions.js'

// Store
const store = new Vuex.Store({
  getters: {
    myGetter: state => {
      // Use the function somewhere
      const isEqual = isMonthEqual(month1, month2)
      return isEqual
    }
  }
})

Upvotes: 3

Related Questions