Vue创建table表格(添加和删除)

首先引入Vue.js

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js"></script>

<div>
        <table id="table">
            <thead>
                 <tr>
                    <th>编号</th>
                     <th>姓名</th>
                     <th>年龄</th>
                     <th>操作</th>
                 </tr>
            </thead>
             <tbody>
                  <tr v-for="(user,index) in stu">
                      <td>{{index+1}}</td>
                      <td>{{user.name}}</td>
                      <td>{{user.age}}</td>
                      <td><button @click="remove(index)">移除</button></td>
                  </tr>
                  <tr>
                      <td></td>
                      <td><input id="name" v-model="user.name"></td>
                      <td><input id="age" v-model="user.age"></td>
                      <td><button @click="insert">添加</button></td>
                  </tr>
            </tbody>
        </table> 
         
   </div>  

写script

<script type="text/javascript">
    new Vue({
      el:'#table',
      data:{
         user:{name:'',age:''},
         stu:[
             {'name': '张三', 'age': 17},
             {'name': '里斯', 'age': 18},
             {'name': '王五', 'age': 19}
         ]
      },
     methods:{
     
       insert:function(){
          this.stu.push(this.user)
       },
       remove:function(index){
         this.stu.splice(index,1)
       }
       
     }
    })
 </script>

注:第一个地方是data数据里面的user:{name:' ',age:' '}千万不能省略,如果省略就所有数据都不显示 

       第二个是insert中this.stu.push(this.user)是添加里面的user

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值