【问题标题】:How to delete dynamic component in Nuxt.js如何在 Nuxt.js 中删除动态组件
【发布时间】:2020-10-06 06:37:15
【问题描述】:

我将 Nuxt.js 与 Vue.js 一起使用。我添加了这样的动态组件。

// pages/index.vue
<template>
  <div class="filter-container">
    <component v-for="item in buttons" :is="item" :key="item.id" :buttons="buttons" />
    <span class="add-search" @click="add">ADD</span>
  </div>
</template>

<script>
const dynamicComponentFilter = () => import("@/components/ProductFilter");

export default {
  data() {
    return {
      buttons: []
    }
  },

  methods: {
    add() {
      this.buttons.push(dynamicComponentFilter);
    }
  }
}
</script>

在组件中

// components/productFilter.vue
<template>
..........
  <span class="del" @click="delQuerysToStore(item)">del</span>
..
..
..
</template>

<script>
export default {
  props: ["buttons", "item"],

  methods: {
  delQuerysToStore(item) {
      this.buttons.splice(this.buttons.indexOf(item), 1);
    }
  }
}
</script>

像这样。 当我单击添加按钮时,每次单击都会出现组件。 当我单击 del 按钮时,然后删除最后一个组件... 我想删除与我单击的按钮相对应的组件。

为什么 indexOf 不起作用?我看了console.log(this.buttons.indexOf(item));,它确实有效!当我单击第二个按钮时,出现索引 1。但是为什么在组件上不起作用?

【问题讨论】:

    标签: javascript vue.js nuxt.js


    【解决方案1】:

    我认为您无权访问components/productFilter.vue 中的this.buttons,因为this.buttons 的范围仅限于其组件实例,并且在道具中提供它并期望其父级中的反应性不是一个好习惯。我建议你通过props item-id 传递这个动态组件的索引,然后在delQuerysToStore() 中发出一个事件,然后在父pages/index.vue 中删除该组件。示例:

    // components/productFilter.vue
    
     props: {
       itemId: {
         type: Number,
         default: 0
       }
    },
     methods: {
      delQuerysToStore(item) {
          this.$emit('delete', this.itemId)
        }
      }
    }
    
    // pages/index.vue
    
    <template>
      <div class="filter-container">
        <component v-for="(item, index) in buttons" :is="item" :key="item.id" :buttons="buttons" @delete="deleteComponent" :item-id="index"/>
        <span class="add-search" @click="add">ADD</span>
      </div>
    </template>
    
    <script>
    const dynamicComponentFilter = () => import("@/components/ProductFilter");
    
    export default {
      data() {
        return {
          buttons: []
        }
      },
    
      methods: {
        add() {
          this.buttons.push(dynamicComponentFilter);
        },
        deleteComponent(itemId) {
         this.buttons.splice(itemId, 1)
        }
      }
    }
    </script>
    

    一般来说,这是标准和良好的做法:数据向下 -> 动作向上。您将数据提供给较低级别​​的组件,但较低级别的组件会向其父级发送事件,因此组件之间的通信工作。

    【讨论】:

    • 数据到较低级别的组件!我得到了它。我不知道,所以我所有的应用程序都是这样的......谢谢你的教导!
    猜你喜欢
    • 2019-10-14
    • 2021-01-17
    • 2019-02-20
    • 2021-02-26
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2012-02-28
    相关资源
    最近更新 更多