切换对象属性VueJS?

时间:2020-07-02 18:09:47

标签: javascript vue.js vuetify.js

我有一个数组cars,它向我返回名称,每个名称都有一个属性starred,我想来回切换真假。但是我想一次只将其中一个设为星标为true。因此,我创建了一个方法setStarred,并且在该方法内部,我使用了map将其他值设置为false。但是我可以将星标设置为true,但是我不能将其设置为false。

请检查此Codepen

这是可行的示例

new Vue({
  el: "#app",
  data() {
    return {
      cars: [{
          name: "Toyota",
          starred: false
        },
        {
          name: "BMW",
          starred: false
        },
        {
          name: "Ford",
          starred: false
        }
      ]
    };
  },
  methods: {
    setStarred(index) {
      this.cars.map((i) => {
        i.starred = false;
      });
      this.cars[index].starred = !this.cars[index].starred;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout justify-center column>
        <v-flex xs6 v-for="(car,index) in cars" :key="index">
          <h2>{{car.name}}
            <v-icon :color="car.starred ? 'primary': '' " @click="setStarred(index)">star_border
            </v-icon>
          </h2>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>
</div>

基本上,我正在尝试将所选内容设置回false。任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

尝试一下:

this.cars[index].starred = !this.cars[index].starred;
this.cars.map((i) => {
     if(i.name!=this.cars[index].name)
          i.starred = false;
});

答案 1 :(得分:1)

我希望先保存目标的“已加星标”状态,然后再进行切换。

如果是这样,则无需在for循环中放置一个 if 语句。尽管在这种情况下,它并不能改善很多性能,但是我相信避免如果来自 for 循环是一个好习惯。

下面是示例:

new Vue({
  el: "#app",
  data() {
    return {
      cars: [{
          name: "Toyota",
          starred: false
        },
        {
          name: "BMW",
          starred: false
        },
        {
          name: "Ford",
          starred: false
        }
      ]
    };
  },
  methods: {
    setStarred(index) {
      let cur = this.cars[index].starred
      this.cars.forEach((i) => {
        i.starred = false;
      });
      this.cars[index].starred = !cur;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.18/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout justify-center column>
        <v-flex xs6 v-for="(car,index) in cars" :key="index">
          <h2>{{car.name}}
            <v-icon :color="car.starred ? 'primary': '' " @click="setStarred(index)">star_border
            </v-icon>
          </h2>
        </v-flex>
      </v-layout>
    </v-container>
  </v-app>
</div>