【问题标题】:Vue delete child componentvue删除子组件
【发布时间】:2018-01-24 08:52:09
【问题描述】:

我有这个代码:

Vue.component('parent', {
  template: `
    <div>
      <child v-for='(child, index) in children' :key='index' :childNumber="index+1" v-on:removeChild="removeChild" />
    </div>
  `,
  data: function() {
    return {
      children: [{}, {}, {}]
    }
  },
  methods: {
    removeChild: function(index) {
      this.children.splice(index, 1);
    }
  }
});

Vue.component('child', {
  template: `
    <div>
      <input :value="'I am child number: '+childNumber"></input>
      <button v-on:click="removeChild">Remove child {{childNumber}}</button>
    </div>
  `,
  data: function() {
    return {}
  },
  methods: {
    removeChild: function() {
      this.$emit('removeChild', this.childNumber);
    }
  },
  props: ['childNumber']
});

const app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
    }
});

当您单击任何“删除”按钮时,它会删除最后一个子项,无论您单击了哪个按钮。如何更改我的代码以删除您认为它将删除的孩子,而不触及其他孩子? (即点击“移除孩子 2”将在屏幕上只留下孩子 1 和 3)

小提琴:https://jsfiddle.net/wgr3sxqr/6/

【问题讨论】:

    标签: vue.js components


    【解决方案1】:

    使用空子时,您无法查看更改。

    您面临的问题是:

    在您删除任何子(假设子 1) 后,组件将重新渲染。而且由于您的命名仅基于索引,因此您将始终看到左侧的孩子(1 和 2)。原因是因为孩子 2 变成了 1,孩子 3 变成了 2,依此类推。

    解决方案

    尝试为每个组件添加name 属性以查看差异。也因为childNumberindex + 1 你必须在删除方法中从索引中减去1

    这是您的案例的有效Fiddle

    这是更新后的代码:

    Vue.component('parent', {
      template: `
        <div>
          <child v-for='(child, index) in children' :key='index' :childNumber="index+1" 
                 v-on:removeChild="removeChild" :name="child.name"/>
        </div>
      `,
      data: function() {
        return {
          children: [{name: 'child 1'}, {name: 'child 2'}, {name: 'child 3'}]
        }
      },
      methods: {
        removeChild: function(index) {
          this.children.splice(index - 1, 1);
        }
      }
    });
    
    Vue.component('child', {
      template: `
        <div>
          <input :value="'I am ' + name"></p>
          <button v-on:click="removeChild">Remove {{name}}</button>
        </div>
      `,
      data: function() {
        return {}
      },
      methods: {
        removeChild: function() {
          this.$emit('removeChild', this.childNumber);
        }
      },
      props: ['childNumber', 'name']
    });
    const app = new Vue({
        el: '#app',
        data: {
            message: 'Hello Vue!',
        }
    });
    

    【讨论】:

    • 完美。谢谢。
    猜你喜欢
    • 2017-03-04
    • 2019-11-20
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2018-01-18
    • 2020-11-02
    相关资源
    最近更新 更多