最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert v-model value from number to string - Stack Overflow

programmeradmin0浏览0评论

I am using <q-select> ponent 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
  autoplete
  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?

I am using <q-select> ponent 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
  autoplete
  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?

Share Improve this question asked May 10, 2020 at 17:41 kavkaxkavkax 953 gold badges4 silver badges10 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

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

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

And then use the puted method as the model

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

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

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();
  <s-select
   autoplete
   sorted
   :value="data.id.toString()"
   options="list"
   option-value="value"
   option-label="label"
   label="Field"
   required
  />

I suggest using a puted property for that

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

Your template will be cleaner and stays reactive

<s-select
  autoplete
  sorted
  v-model="id"
  options="list"
  option-value="value"
  option-label="label"
  label="Field"
  required
 />
发布评论

评论列表(0)

  1. 暂无评论