使用v-for循环渲染组件时如何有效删除特定组件

时间:2017-10-11 12:00:37

标签: javascript vue.js vuejs2 vue-component

大家和任何人,

我在vue.js 2项目中使用v-for循环来渲染一些组件,

基本上有一个具有属性计数的包装器组件

并且对于count的值,它迭代并创建子组件的计数,如此

// inventory.vue
template(
    v-for="(resource, index) in resourcesMutable" 
    )
    resource(
      v-if="resource && resource.description && typeof resource === 'object'"
      :resource="resource"
      :index="index"
      :key="resource._id"
      :options="resourceOptions"
      :style="{order: 2}"
      :neighbours="resourcesMutable"
      )
    resource(
      v-else-if="resource == undefined"
      :index="index"
      :key="index"
      :options="resourceOptions"
      :style="{order: 2}"
      :neighbours="resourcesMutable"
      )

现在的问题是,每个子组件都需要有一个函数,可以从用于呈现它们的resourcesMutable列表中删除它。

我所做的是将每个列表项的索引传递给子项,然后添加了一个deleteResource函数,该函数拼接父的resourcesMutable数组以删除用户删除的组件。

Buuuut,这有一种意料之外的行为,即下一个兄弟会隐藏已删除组件的当前数据。

以下是删除资源的方法

// resource.vue
deleteResource(){
      this.neighboursMutable.splice(this.index, 1)
    },

以下是我处理密钥的方式,

// resource.vue
computed: {
    resourceMutable: {
      get: function(){
        let value = this.resource || {
          description: "Start typing to create a new post, the first line or 200 characters will be used as the title unless otherwise chosen below",
          resource: 'new resource',
          uuid: this._uid
        }
        this.resource = value
        this.neighboursMutable[this.index] = value
        this.key = value.uuid
        // console.log(this.resourceMutable.uuid)
        return value
      }
    }
  },

现在你可能想知道为什么我在组件的属性的getter中设置键,那是因为父组件需要支持向列表中添加项,所以有一个按钮只是将未定义的列添加到列表中v-for'd,

因为在我看来,父组件不需要为呈现的子组件保留任何默认值,孩子应该处理它,

但vue.js有这个奇怪的事情,当undefined作为属性传递时,属性不使用它的默认值,而是意味着你必须在计算的可变变量中执行此操作,这很好,但它也意味着我不能只设置:key =“resource.id”或任何id,

无论如何,你打算用什么作为v-for'd数据的关键,他们真的希望每个迭代列表都有列表项的id?

所以我在创建组件后设置了密钥

我认为这实际上工作正常

当我向列表添加一些项目时,我得到的输出看起来有点像这样

item 0, this.key = 1329, this.index = 0
item 1, this.key = 1349, this.index = 1
item 2, this.key = 1379, this.index = 2 ( make this.options = ['woo'] )
item 3, this.key = 1419, this.index = 3
item 4, this.key = 1429, this.index = 4

但是,让我说我改变了第2项的状态,并使this.options = ['woo']

然后去

item 0, this.key = 1329, this.index = 0
item 1, this.key = 1349, this.index = 1
item 2, this.key = 1379, this.index = 2 ( click deleteResource )
item 3, this.key = 1419, this.index = 3
item 4, this.key = 1429, this.index = 4

然后新输出看起来像这样

item 0, this.key = 1329, this.index = 0
item 1, this.key = 1349, this.index = 1
item 2, this.key = 1419, this.index = 2 ( but this component, with a different key, has this.options = ['woo'] )
item 3, this.key = 1429, this.index = 3

所以那里发生了什么?

哦,我正在谈论的选项甚至通过

转换为单向绑定
this.optionsMutable = JSON.parse(JSON.stringify(this.options))

所以,我不明白._uid为1的组件如何将其数据状态传递给另一个具有不同._uid的组件,

任何想法?

0 个答案:

没有答案