动态地将属性添加到数组中的对象

时间:2020-03-29 13:04:59

标签: vue.js vuejs2 vue-component

我试图在数组内的对象中添加一个属性,但我无法使其工作:

因此,我正在将一个数组传递给包含Names.vue的{​​{1}},并且当用户将鼠标悬停在该名称上时,我试图在该名称旁边显示一些图标: A live example of the problem

Names.vue

['John', 'Jane']

但这行不通吗?为什么?

2 个答案:

答案 0 :(得分:0)

您未声明showIcons。要解决此问题,请更新您的App.vue文件:

data() {
    return {
         names: [
             { name: "John", showIcons: false },
             { name: "Jane", showIcons: false }
         ]
    };
}

还有您的姓名。

<template>
     <div>
          <ul>
               <li v-for="(name, index) in names" :key="index">
                    <span @mouseenter="name.showIcons = true" @mouseleave="name.showIcons = 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
     }
};
</script>

答案 1 :(得分:0)

或者-您可以使用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>