简体   繁体   English

VueJS如何将v-model与数组的特定元素一起使用?

[英]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".在具有“/playlistid”路由的“播放列表页面”中,有一个复选框,我将其用作“喜欢按钮”。

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.基本上我从我的服务器加载一个数组(我们称之为“收藏夹”),当你点击喜欢时,我从单个页面的 this.$route.params.id 中获取 ID。

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?现在,我如何将 v-model 与我的本地(加载)数组绑定,以检查 $route.params.id 是否包含在其中,并检查最后一次检查是否为真输入?

This is my code.这是我的代码。

HTML side: HTML 侧:

<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?在 v-model 中使用 contains() 或 indexOf() 显然不起作用,那么我该怎么做呢? Thanks in advance for the help.在此先感谢您的帮助。

I think you're trying to use v-model wrong.我认为您试图错误地使用 v-model 。 v-model is used for two-way binding of your components data to be reactive to events. v-model 用于组件数据的双向绑定以响应事件。 So, if you want to store the values of all the selected fav movies, you can do it very simply using the v-model.因此,如果您想存储所有选定的喜爱电影的值,您可以使用 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.因此,如果我们选中 Best One,则该电影的值将 go 放入数组中,如果我们取消选中它,该值将从该数组中弹出。 You can add as many as you like, and use the same piece of state from our data.您可以根据需要添加任意数量,并使用我们数据中的同一块 state。 It's pretty magical that view lets us do this.视图让我们这样做是非常神奇的。 Check out more great examples in the docs here在此处的文档中查看更多出色的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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