【问题标题】:How to remove vue non-props component instance?如何移除 vue 非 props 组件实例?
【发布时间】:2021-10-25 09:51:15
【问题描述】:

我们可以移除/删除 Vue 意外渲染的非 props 组件实例吗? 我尝试使用inheritAttrs: false(但不包括在组件道具和发射属性中)或deleteThisComponent(idx{this.idx.splice(this.idx.indexOf(idx, 1))},但它没有用。

我需要删除它们,因为它不应该存在,在我的情况下,它应该只是带有渲染道具的组件实例。请参阅下面的 Vue 组件检查。

P.S 我想删除 4 和 5,他们没有任何道具。即使我没有为索引 4 和 5 的数据属性设置任何值。

这是我的非工作代码, 在 MyTab.html 上,它更像是骨架

<div class="tab__header">
      <a
        v-for="(tab, idx) in tabs"
        v-bind="$attrs"
        :class="class(idx)"
        :key="idx"
        tabindex="0">
        <span class="tab__icon" v-if="hasIcon">
          <component :is="tabTitle.icon" />
        </span>
        {{ tabTitle.title}}
      </a>
    </div>

并以 Tab.js 作为基础 js。

export default {
  inheritAttrs: false,
  data() {
    return {
      tabs: []
    }
  },
  created() {
    this.tabs = this.$children //I also wonder, is the problem is from here or not? Since normal Javascript patterns here used to get all of the children.
  }
//....
}

这里是包含模板和数据属性的tab.js,

//....
myTabTemplate: `
 <div>
   <MyTab>
     <TabHeader
       v-for="(tab, idx) in tabs"
       :key="idx"
       :title="tab.title"
       :icon="tab.icon">
       <h3>Heading {{idx + 1}}</h3> {{ tab.title}}
      </TabHeader>
   </MyTab>
 </div>
`,
myTabScript: {
 data () {
   return {
     items: [
      {
       icon: `User`,
       title:'First Tab'
      },
      {
       icon: `Wishlist`,
       title:'Second Tab'
      },
      {
       title:'Third Tab'
      }, 
      {
       title:'Fourth Tab'
      }
     ]
   }
 }
},

【问题讨论】:

  • 什么是vue non-props component instance?你的意思是只渲染并且不包含任何道具的愚蠢组件?
  • @flx 这是非道具属性。 “组件非prop属性是传递给组件的属性或事件侦听器,但在props或emits中没有定义相应的属性。” - v3.vuejs.org/guide/component-attrs.html#attribute-inheritance
  • 啊好吧。您可以使用 inheritAttrs: false 显示您的非工作代码(或类似示例)吗?
  • 当然@flx,已根据上述问题进行了编辑。

标签: javascript vue.js vue-component


【解决方案1】:

您可以在分配给 v-for 的资源之前添加过滤条件。

你的例子:

tab.js

  created() {
    this.tabs = this.$children.filter(child => {
        const hasProps = !!child.$options.props;
        return hasProps;
    })
  }

【讨论】:

  • 哦,它工作得很好!但不是在 created() 中,非常感谢@Chunbin Li
  • 这取决于您何时要过滤,您可以将过滤逻辑移动到任何方法或根据您的功能挂钩。关键是你必须过滤 v-for 数据并重新分配它。
猜你喜欢
  • 2016-10-22
  • 2023-03-18
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
  • 2018-03-22
  • 2020-07-02
  • 2020-09-22
相关资源
最近更新 更多