Skip to content
Advertisement

Link v-model to a object’s property in Vue.js 2

I use Vue.js 2 and I have this array, obtained from this API call (https://developers.themoviedb.org/3/genres/get-movie-list this one) that I’ve used to make a select in HTML:

 "genres": [
        {
            "id": 28,
            "name": "Azione"
        },
        {
            "id": 12,
            "name": "Avventura"
        },
        {
            "id": 16,
            "name": "Animazione"
        },
        {
            "id": 35,
            "name": "Commedia"
        },
        {
            "id": 80,
            "name": "Crime"
        },
        {
            "id": 99,
            "name": "Documentario"
        },
        {
            "id": 18,
            "name": "Dramma"
        },
        {
            "id": 10751,
            "name": "Famiglia"
        },
        {
            "id": 14,
            "name": "Fantasy"
        },
        {
            "id": 36,
            "name": "Storia"
        },
        {
            "id": 27,
            "name": "Horror"
        },
        {
            "id": 10402,
            "name": "Musica"
        },
        {
            "id": 9648,
            "name": "Mistero"
        },
        {
            "id": 10749,
            "name": "Romance"
        },
        {
            "id": 878,
            "name": "Fantascienza"
        },
        {
            "id": 10770,
            "name": "televisione film"
        },
        {
            "id": 53,
            "name": "Thriller"
        },
        {
            "id": 10752,
            "name": "Guerra"
        },
        {
            "id": 37,
            "name": "Western"
        }
    ]
}

What I want is to link the v-model, which is declared in Js as an empty string, to the property id of this array. I can’t extract the property and use an array with only it, because options’ name is a v-for that prints genres.name At the point I am now when I do the console.log on the v-model it returns an empty string, means that v-model doesn’t take any value. The select is this:

        <label for="title">Title</label>
        <select id="title" name="title"
        @change="filterAlbums(selectedGenre)"
        v-model="selectedGenre">
            <option value="">All</option>
            <option v-for="genre in genresName" value="">{{genre.name}}</option>
        </select>

In data the v-model variable is declared this way:

selectedGenre: '',

I check the v-model status here in this function

filterAlbums(selectedGenre) {
   console.log(selectedGenre);
        }

Advertisement

Answer

Do you mean that this array is a list of elements to be options in a select? If yes, you need to bind every option value (previously generated in a loop by v-for) with the element id:

<select v-model="someValueWithInitialEmptyString">
   <option v-for="element in genres" :key="element.id" :value="element.id">
      {{element.name}}
   </option>
</select>
Advertisement