Max Pattern
Max Pattern

Reputation: 1688

Vue 3 "Uncaught ReferenceError: {varName} is not defined" only if a build the app

I am currently working on a VueJS 3 app. In developer mode everything works fine. But as soon as I build (npm run build) it, I have a place in the app (selectbox whose data comes from an api) where I get an error:

Uncaught ReferenceError: selectedCountry is not defined

The rest of the app works fine.

The location of the compiled JS file. The "isRef(..)" makes trouble!

...($event) => isRef(selectedCountry) ? selectedCountry.value = $event : null)...
               ^^^^^

Part from the vue file

  data() {
    return {
      countries: [],
      cities: [],
      selectedCountry: "",
      selectedRoute: "",
      selectedCity: "",
   },
  methods: {
    async getCountries() {
      this.countries = await store.getCountries();
    },
    async getCities() {
      console.log(this.selectedCountry); // <empty string>
      const countryId = this.selectedCountry;
      this.cities = await store.getCities(countryId);
    },

and a part from the html

<select v-model="selectedCountry" @change="getCities">
      <option>Select Country</option>
      <option v-for="country in countries" :key="country.id" 
        :value="{countryId: country.id, text: country.name}">
        {{ country.name }}
      </option>
</select>

I find the error strange because it only happens when I build. Can a helper help me? Thanks in advance!

What I have found

I have found that in the built state, the Select choice is not bound. And i git a <empty string>.

Upvotes: 4

Views: 2013

Answers (1)

Max Pattern
Max Pattern

Reputation: 1688

I have figured it out. Usually this error occurs if you do not register the varible in data() or have declared it in the scope of a function.

Another source of error could be that you do not have a first default line in the options. Especially with MacOs systems. So you should add this line:

<option disabled value="">Please select one</option>.

If the initial value of your v-model expression does not match any of the options, the element will render in an "unselected" state. On iOS this will cause the user not being able to select the first item because iOS does not fire a change event in this case. It is therefore recommended to provide a disabled option with an empty value, as demonstrated in the example above. https://vuejs.org/guide/essentials/forms.html#select

What caused the error for me?

But that is not the case in this particular instance. The problem here was an empty

<script setup> 
  // import TheWelcome from "@/components/TheWelcome.vue"; 
</script>

tag in the Vue file with the form.

So if you have the same error and you are sure that you have declared the variable, make sure that you don't have two script tags in your single file components. After I deleted the tag, the error disappeared in the built state.

Upvotes: 1

Related Questions