我的 Vue.js 学习日记 (六) - v-for 与 table 的 增、删、排序、明细

上节回顾

上一节把v-ifv-show看完了,心里默默回想一下他们的用法与注意事项

v-for

最近加班回来的比较晚,没什么时间,今天就基于v-for写一个中规中矩例子吧

下面是一个带有打印明细排序的基于 v-fortable 的例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <!-- 开发环境版本,包含了用帮助的命令行警告 -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>chapter - 6</title>
</head>
<body>
<div id="app">
  <table>
    <tr>
      <th>index</th>
      <th>key</th>
      <th>value <button @click="doSort">点我排序</button></th>
      <th>操作</th>
    </tr>
    <tr>
      <td></td>
      <td><input type="text" v-model="id" placeholder="input -> id"></td>
      <td><input type="text" v-model="name" placeholder="input -> name"></td>
      <td><button @click="addObj(id, name)">add</button></td>
    </tr>
    <tr v-for="(item, index) in items" :key="item.id">
      <td>{{index}}</td>
      <td>{{item.id}}</td>
      <td>{{item.name}}</td>
      <td>
        <button @click="printObj(item)">打印对象</button>
        <button @click="removeObj(index)">移除对象</button>
      </td>
    </tr>
  </table>
</div>

<script>
  const data = {
    id: '',
    name: '',
    items: [
      {id: 1, name: 'name - 1'},
      {id: 2, name: 'name - 3'},
      {id: 3, name: 'name - 2'}
    ]
  }

  const methods= {
    printObj (obj) {
      console.log(obj.id + ' - '+obj.name )
    },
    removeObj (item) {
      this.items.splice(item,1)
    },
    addObj (id, name) {
      this.items.push({id: id, name: name})
    },
    doSort () {
      this.items.reverse(this.items.key)
    }
  }

 var vm = new Vue({
   el: '#app',
   data: data,
   methods: methods
 })
</script>
</body>
</html>

小节

table是很常见的元素,那么基于table的操作也变得很常见,希望以后忘记了如何编写这些基础操作的时候来这里能快速的记忆起来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值