Skip to content
Advertisement

Typecasting v-for key Vue

I am creating a v-for list based on a range that I am suppling my component:

<div class="checkbox" v-for="(value, key) in range">

I am suppling my data as a prop like so:

"{ 0: '0 stars', 1: '1 star', 2: '2 stars' }"

My v-for key will always be set as a string though when I log typeof. This is strange since I am passing an object which holds the key as a number and not a string.

I do not want to typecast it constantly when I pass the key along to a method. Is there a way to typecast it easily?

Also what could be causing this to come out as a string instead of a int?

Whenever I console.log my range object the keys appear in purple so I am guessing at that point they are still viewed as ints?

Advertisement

Answer

In JavaScript objects the keys are always strings. It you provide a key that is not a string then its automatically converted to string by javascript. AFAIK it is by design choice .See Object.keys()

You can pass index as your third argumemt like this:

<div class="checkbox" v-for="(value, key, index) in range">

And pass index to your method but as vuejs warns(here):

When iterating over an object, the order is based on the key enumeration order of Object.keys(), which is not guaranteed to be consistent across JavaScript engine implementations.

Its better to cast like this myMethod(Number(key))

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement