Vue组件:组件的动态添加与删除

一、实现效果

1074798-20180915162925405-266354048.gif

二、实现代码

HelloWorld.vue

<template>
  <div class="hello">
    <child-page v-for="(item,index) in items"
      :key="index"
      :index="index"
      :items="items"
      @deleteIndex="del"
      @uploadData="getData">
    </child-page>
    <button @click="add">Add</button>
  </div>
</template>

<script>
import ChildPage from './ChildPage'
export default {
  data () {
    return {
      items: [{}],
      dataRec: []
    }
  },
  components: {
    ChildPage
  },
  methods: {
    //  add student
    add: function () {
      this.items.push({name: '', age: ''})
    },
    // delete student
    del: function (index) {
      //  not allow to delete the first
      if (index !== 0) {
        this.items.splice(index, 1)
        console.log('deleted:', JSON.stringify(this.items))
      }
    },
    //  get the data from child
    getData: function (val) {
      let index = val.index
      this.items[index] = val.data
      console.log('I got the data:', JSON.stringify(this.items))
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

ChildPage.vue

<template>
  <div class="hello">
      <h1>Component:{{index}}</h1>
      <p>Name:<input type="text" v-model="student.name" placeholder="Please enter name"></p>
      <p>Age:<input type="text" v-model="student.age" placeholder="Please enter age"><button @click="deleteStudent">Delete</button></p>
  </div>
</template>

<script>
export default {
  props: {
    index: {
      type: Number,
      required: true
    },
    items: {
      type: Array,
      default: Array
    }
  },
  data () {
    return {
      student: {
        name: '',
        age: ''
      }
    }
  },
  watch: {
    student: {
      handler (newV, oldV) {
        if (newV.name.length === 0) {
          return false
        }
        if (newV.age.length === 0) {
          return false
        }

        this.$emit('uploadData', {index: this.index, data: newV})
      },
      deep: true
    },
    items: {
      handler (newV, oldV) {
        if (newV.length !== 0) {
          this.student = {...newV[this.index]}
        }
      },
      deep: true
    }
  },
  methods: {
    deleteStudent: function () {
      this.$emit('deleteIndex', this.index)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

转载于:https://www.cnblogs.com/yejingping/p/9651297.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值