【问题标题】:show element in v-for list: VueJS [duplicate]在 v-for 列表中显示元素:VueJS [重复]
【发布时间】:2020-04-22 06:09:50
【问题描述】:

我有一个 v-for,它显示我的所有项目,并且每个项目都有一个面板(用于修改和删除),但是当我单击此按钮以显示我的面板时,它会出现在我的所有项目上。我怎样才能避免这种情况?当我点击修改按钮时,这是同样的事情,修改我的项目的输入出现在每个元素上。

这是我的代码:

<div v-for="(comment, index) in comments" :list="index" :key="comment">
   <div v-on:click="show = !show">
      <div v-if="show">
         <button @click="edit(comment), active = !active, inactive = !inactive">
            Modify
         </button>
         <button @click="deleteComment(comment)">
            Delete
         </button>
      </div>
   </div>
   <div>
      <p :class="{ active: active }">
        {{ comment.content }}
      </p>
      <input :class="{ inactive: inactive }" type="text" v-model="comment.content" @keyup.enter="doneEdit">
   </div>
</div>

以及方法和数据:

data() {
  return {
    show: false,
    editing: null,
    active: true,
    inactive: true
  }
},

methods: {
   edit(comment) {
     this.editing = comment
     this.oldComment = comment.content
   },

   doneEdit() {
     this.editing = null
     this.active = true
     this.inactive = true
   }
}

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    所有项目的showeditingactiveinactive 状态相同。因此,如果您更改一项的某些数据属性,它会更改所有项。 有很多方法可以实现您想要的。

    最简单的方法是按索引管理数据。 例如:

    <div v-on:click="showIndex = index">
      <div v-if="showIndex === index">
      ...
    data () {
      return {
        showIndex: null
      ...
    

    这种方法的主要问题 - 您一次只能显示/编辑一个项目。 如果您需要更复杂的逻辑并且想管理多个项目,我建议为您的项目创建一个单独的组件,每个组件都有自己的状态(showediting 等)

    【讨论】:

    • 谢谢你的回答,我马上去测试!
    【解决方案2】:

    @NaN 的方法适用于您一次只打开一个。如果您希望有可能同时打开多个,则需要跟踪每个单独的元素。现在你只是基于show。对于所有元素,它只能是true/false

    所以这就是你需要做的:

    show 从布尔值更改为数组

    data() {
      return {
        show: [],
        editing: null,
        active: true,
        inactive: true,
    
      }
    },
    

    然后你可以跟踪哪个元素应该有面板:

    <div v-on:click="toggleActive(index)">
    

    以及方法:

    methods: {
       toggleActive(index) {
          if (this.show.includes(index)) {
            this.show = this.show.filter(entry => entry !== index);
    
            return; 
          }
    
          this.show.push(index);
       }
    }
    

    最后你的v-if 变成:

    <div v-if="show.includes(index)">
    

    【讨论】:

    • NaN 方法是一个很好的方法,但我会测试你的方法并决定我是采用你的方法还是 NaN 方法,非常感谢你的回答!
    猜你喜欢
    • 2019-09-13
    • 2017-06-03
    • 1970-01-01
    • 2019-12-19
    • 2021-07-06
    • 2018-04-27
    • 2020-06-29
    • 2020-08-19
    • 2019-04-04
    相关资源
    最近更新 更多