简体   繁体   中英

VueJS how to use v-model with a specific element of an array?

I'm developing a website where you can create, view and like playlists of movies.

In the "playlist page", which has a "/playlistid" route there is a checkbox that I use as a "like button".

Basically I load an array from my server (let's call it "favorites") with the IDs that I take from this.$route.params.id of the single pages, when you click like.

Now, how do I bind the v-model with my local (loaded) array, to check if $route.params.id is included inside, and make the input checked if this last check is true?

This is my code.

HTML side:

<label v-if="like" class="ml-2">
   <input type="checkbox" class="heart" @change="checkLike" v-model='favorites.includes(this.$route.params.id)'>
   <span></span>
</label>

SCRIPT side:

data () {
      return {
        favorites: []
      }
},
methods: {
   checkLike() {
      if (this.favorites.includes(this.$route.params.id)) {

            this.favorites.splice(this.$route.params.id, 1);
            axios.patch(...)

      } else if (!this.favorites.includes(this.$route.params.id)) {

            this.favorites.push(this.$route.params.id)
            axios.patch(...)

      }
   }

Using contains() or indexOf() inside v-model clearly doesn't work, so how could I do this? Thanks in advance for the help.

I think you're trying to use v-model wrong. v-model is used for two-way binding of your components data to be reactive to events. So, if you want to store the values of all the selected fav movies, you can do it very simply using the v-model.

<input type="checkbox" id="1" value="movie1" v-model="favorites">
<label for="movie1">Best One</label>

<input type="checkbox" id="2" value="movie2" v-model="favorites">
<label for="movie2">Okay movie</label>
    data () {
      return {
        favorites: []
      }
   },

Now the selection of each of those checkboxes will stay up-to-date with our data's values. So if we check Best One, the value for that movie will go into the array, and if we uncheck it, the value will be popped out of that array. You can add as many as you like, and use the same piece of state from our data. It's pretty magical that view lets us do this. Check out more great examples in the docs here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM