Kawd
Kawd

Reputation: 4450

Vue.js | ReferenceError: Model property is undefined on input change

The following Vue.js v3 component file :

// src/components/Unlock.vue

<script setup>
  import axios from 'axios'
</script>

<script>

  export default {
    data() {
      return {
        username:'',
        hash: ''
      }
    },

    methods: {
      unlock() {
        let username = this.username ? this.username.trim() : ''
        let hash = this.hash ? this.hash.trim() : ''
        if (username.length && hash.length) {
          axios.post('/unlock', { username, hash }).then(({ data }) => {
            this.$router.push(`/unlocked/${data.index}`)
          }).catch((error) => {
            console.error(error)
          })
        }
      }
    }
  }

</script>

<template>
  <div>
    <input v-model="username"
           type="text"
           placeholder="username">
    <br>
    <input v-model="hash"
           type="text"
           placeholder="redeem code">
    <br>
    <button type="button" @click="unlock">CLICK HERE TO UNLOCK</button>
  </div>
</template>

Is throwing the following Errors whenever I start typing in any of the two inputs:

index.e65df20f.js:1 Uncaught ReferenceError: username is not defined
    at HTMLInputElement.s.onUpdate:modelValue.a.<computed>.a.<computed> [as _assign] (index.e65df20f.js:1:3237)
    at HTMLInputElement.<anonymous> (vendor.7ec322db.js:1:53128)

and

index.e65df20f.js:1 Uncaught ReferenceError: hash is not defined
    at HTMLInputElement.s.onUpdate:modelValue.a.<computed>.a.<computed> [as _assign] (index.e65df20f.js:1:3237)
    at HTMLInputElement.<anonymous> (vendor.7ec322db.js:1:53128)

But I cannot spot what I'm doing wrong

You can replicate the problem on codesandbox.io

Remember to open your browser's console to see the errors as soon as you start typing in any of the inputs. They will not show up on the "console" of the sandbox GUI.

Upvotes: 0

Views: 1476

Answers (1)

tao
tao

Reputation: 90068

Do not instantiate reactive properties (e.g: username, hash) with undefined.

Instantiate with null (or whatever falsey value makes sense for that prop: empty array, 0, empty string, etc...).

In the above case, both reactive props should be instantiated with empty string:

data: () => ({
  username: '',
  hash: ''
})

If you instantiate with undefined, it's exactly as if you didn't declare it at all. Hence, your current error: you haven't actually declared either username or hash.


If you're using TypeScript, it's a very good idea to replace

export default {...}

with

import { defineComponent } from 'vue';
export default defineComponent({...})

Upvotes: 1

Related Questions