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
  • Try import * as countryList ? Otherwise you can also do export const countries = [ ... ]; then import { countries } from './config/country_list'; Commented Jul 9, 2021 at 9:37
  • 1
    I think you need to show where you are writing the const countries =... line Commented Jul 9, 2021 at 9:41
  • I am using it in a utils.js file. I need to import main.js file here ? Commented Jul 9, 2021 at 9:47
  • @JeremyThille I tried it, but it is showing the same error. Commented Jul 9, 2021 at 9:48
  • 1
    the function in utils.js file which uses const countries = this.$countryData.countries when do you call it? Commented Jul 9, 2021 at 10:00

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.