[Vuejs]-Dynamically add a property to an object in an array

0👍

Alternatively – you can use this.$set:

<template>
  <div id="app">
    <Names :names="names"/>
  </div>
</template>

<script>
import Names from "./components/Names";

export default {
  name: "App",
  components: {
    Names
  },
  data() {
    return {
      names: [{ name: "John" }, { name: "Jane" }]
    };
  }
};
</script>

<template>
  <div>
    <ul>
      <li v-for="(name, index) in names" :key="index">
        <span
          @mouseenter="setIconsState(index, true)"
          @mouseleave="setIconsState(index, false)"
        >{{ name.name }}</span>
        <span v-if="name.showIcons" style="margin-left:10px">icons</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    names: Array
  },
  methods: {
    setIconsState(index, isShow) {
      this.$set(this.names[index], `showIcons`, isShow);
    }
  }
};
</script>

Leave a comment