v-selectでオブジェクトを取得する

  • 2021年7月7日
  • 2023年2月15日
  • Vue.js
  • 8954view

vuetify2でよく使うv-selectタグ。
先日、これで要素を選択した時に$emitで親にオブジェクトで値を渡したいと思う事がありました。
nameとIdの両方を送りたい!とかそんな感じです。)

「そんなの簡単じゃん!」と思うかもしれませんが、意外と苦労したのでその経緯と対処法をまとめます。

ちなみに結論となる解決法は「return-objectを使う」というシンプルなものです!
詳しくみたい方は記事を読み進めて下さい。
全体のサンプルコードはcodesandboxにあげています。

選択時のvalueはオブジェクトでは帰ってこない

v-selectの初期設定として選択時のvalueはオブジェクトを返しません。
具体例を見てみましょう。v-selectで好きなお菓子の名前とIdを受け取るセレクトボックスです。

v-select部分

<template>
  <v-app id="app">
    値: {{ selectedSweet }}
    <v-select
      v-model="selectedSweet"
      item-text="label"
      item-value="value"
      :items="sweets"
      label="好きなお菓子"
    />
  </v-app>
</template>

ちなみにitem-textとitem-valueを設定する事で、[object, object]と出力されず、labelとsweetIdを出し分け出来ます。

データ定義

  data() {
    return {
      selectedSweet: { label: "チョコ", sweetsId: 1 }, //初期値
      sweets: [
        { label: "チョコ", sweetsId: 1 },
        { label: "バナナ", sweetsId: 2 },
        { label: "グミ", sweetsId: 3 },
      ],
    };
  },

初期値ではオブジェクトの値が取れています。

Image from Gyazo

しかし選択肢を選ぶと…

Image from Gyazo

値にはlabelだけが入ってしまいます。

対処法

簡単です。return-objectを使いましょう。

return-objectはv-selectのpropsで、valueに帰ってくる値がオブジェクトになります。

Image from Gyazo

vuetifyのドキュメント:https://vuetifyjs.com/ja/api/v-select/

先程のv-selectにreturn-objectを入れて

    <v-select
      v-model="selectedSweet"
      item-text="label"
      item-value="value"
      :items="sweets"
      label="好きなお菓子"
      return-object
    />

選択後もちゃんとオブジェクトが取れるようになりました。

Image from Gyazo

まとめ

結論からいうとv-selectはreturn-objectを使う事で、オブジェクトで値を扱える事がわかりました。

v-selectに関わらずvuetifyはラクにUIが作れる反面、細かい挙動の制御が難しいパターンが多いので、詰まった部分が出てきたらまた、本ブログにまとめていきます。

それでは。

初めてweb開発の現場に入った時にVue.jsの勉強用に買った本を思い出に添付。

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Compare ×
Let's Compare! Continue shopping