kavkax
kavkax

Reputation: 95

Convert v-model value from number to string

I am using <q-select> component and inside that i'm sending options that i fetch from API, as value I set id of object, but problem is that it expects string to get and ID is a number and because of that I'm getting error. Is it possible to change type of data inside v-model.

<s-select
  autocomplete
  sorted
  v-model="data.id"
  options="list"
  option-value="value"
  option-label="label"
  label="Field"
  required
 />

I've tried to put data.id.toString() inside v-model but then I got error.

How can i resolve this?

Upvotes: 1

Views: 24250

Answers (4)

Radu Diță
Radu Diță

Reputation: 14191

You can use a computed method with a getter/setter defined.

computed: {
 computedDataId: {
  get() {
    return this.data.id.toString()
  },
  set(val) {
    this.data.id = Number(val)
  }
 }
}

And then use the computed method as the model

<s-select
  autocomplete
  sorted
  v-model="computedDataId"
  options="list"
  option-value="value"
  option-label="label"
  label="Field"
  required
 />

You can also consider converting data.id to a string when getting it.

Upvotes: 3

I suggest using a computed property for that

computed: {
 id: {
   return String(this.data.id);
 }
}

Your template will be cleaner and stays reactive

<s-select
  autocomplete
  sorted
  v-model="id"
  options="list"
  option-value="value"
  option-label="label"
  label="Field"
  required
 />

Upvotes: 0

Abhishek
Abhishek

Reputation: 1

  <s-select
   autocomplete
   sorted
   :value="data.id.toString()"
   options="list"
   option-value="value"
   option-label="label"
   label="Field"
   required
  />

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28424

You cannot apply the method to v-model. One solution would be converting the id to string directly after fetching the data as follows:

let id = data.id;
data.id = id.toString();

Upvotes: 0

Related Questions