Home > Enterprise >  Unable to reference data() in VUEjs Typescript
Unable to reference data() in VUEjs Typescript

Time:04-25

I get error when referencing data() in export. It says, that property does not exist. What am I doing wrong? VueJS version 2.

This is data:

<script lang="ts">
  
export default {
  data() : {
  item: Array<Number> 
  key: Number
  keyy: Number
  } {
  return {
    item: [],
    key: 0,
    keyy: 0,
    };
  },

Here i want to reference it in same export default:

methods: {
      async para(value: any){
        this.key=value.target.value   //Here i get error
    },
      async paraa(value: any){
        this.keyy = value.target.value    //Here i get error
    },
    async openChannels() {
      const randomArray = [0,2]
      this.item.push(randomArray[0])  //Here i get error
    }
}
}
    </script>

The error I am getting is:

Property 'key' does not exist on type '{ para(value: any): Promise; paraa(value: any): Promise; openChannels(): Promise; }'

Property 'keyy' does not exist on type '{ para(value: any): Promise; paraa(value: any): Promise; openChannels(): Promise; }'

Property 'item' does not exist on type '{ para(value: any): Promise; paraa(value: any): Promise; openChannels(): Promise; }'

Thanks for the help.

Ps: My vetur extension does not show any errors. I get these only when compiling code.

CodePudding user response:

If you want TypeScript support you need to use defineComponent

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

I would recommend Volar instead of Vetur.

I would also recommend defining the types closer to the actual values:

data() {
  return {
    item: [] as Array<Number>,
    key: 0 as Number,
    keyy: 0 as Number,
    };
  },

Old answer

randomArray is not defined, you are probably missing const or let

const randomArray = [0,2] // <--

You are missing a } at the end

  }
} // <--
</script>

After these edits, your code should work: Live demo

  • Related