0

I have a country list that is saved as a configuration file country_list. The file has the following contents.

    export default {
      countries: [
        'AUSTRALIA',
        'AUSTRIA',
        'BELGIUM',
        'BRAZIL',
        'BULGARIA',
        'CANADA',
        'CHINA',
        'CROATIA',
        'CYPRUS',
        'CZECHIA',
        'DENMARK',
        'ESTONIA',
        'FINLAND'
    ]
}

Now in the main.js file I am importing it and set it as an instance variable

import countryList from './config/country_list';

Vue.prototype['$countryData'] = countryList;

Now I am trying to access this variable $countries in a file called utils.js like the following :

export const checkCountryIncluded = (country) => {

    const countries = this.$countryData.countries;
    
    return countries.includes(country);
}

and this checkCountryIncluded is called from a component.

But here I am getting an error Uncaught TypeError: Cannot read property 'countries' of undefined

I am new to VueJS and it will be helpful if someone can point out what is missing here.

6

2 Answers 2

1

In separated files like utils the vue instance is not available, it's only available in the components hierarchy, the solution is to pass that global data as parameter when you call your utility function :

this.isCountryIncluded = checkCountryIncluded(this.$countryData,this.country)

utils.js :

export const checkCountryIncluded = (countryData,country) => {

    const countries = countryData.countries;
    
    return countries.includes(country);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can call checkCountryIncluded with the component context.

this.isCountryIncluded = checkCountryIncluded.apply(this, [this.country])

For this to work, the function should be a normal function (non-arrow) since you cannot change the context of arrow functions.

export const checkCountryIncluded = function(country) {

    const countries = this.$countryData.countries;
    
    return countries.includes(country);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.