Vue基础(二)——Vue基础语法案例

案例——图书管理

  • 大致界面如下图所示:

在这里插入图片描述
用户可以在表单输入框中输入编号、图书名称,点击提交后就可以实现图书的添加功能,在图书展示列表中每一行都有修改、删除按钮,点击可以实现相应的修改以及删除功能。

  • 补充知识
    在这里插入图片描述
    在这里插入图片描述

  • 实现步骤:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    .grid {
        /* 水平居中 */
      margin: auto;
      width: 500px;
      text-align: center;
    }
    .grid .aboveTbody {
        width: 100%;
        height: 35px;
        line-height: 35px;
        text-align: center;
        background-color: orange;
        border-bottom: 1px solid greenyellow;
    }
    .grid table {
      width: 100%;
      /* 用于表格属性, 表示表格的两边框合并为一条 */
      border-collapse: collapse;
    }
    .grid th,td {
      padding: 10;
      border: 1px dashed orange;
      height: 35px;
      line-height: 35px;
    }
    .grid th {
      background-color: orange;
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="grid">
      <h1>图书管理</h1>
      <div class="aboveTbody">
        <label for="id">编号 :</label>
        <input type="text" id="id" v-model='id' v-bind:disabled="flag">  
        <label for="name">名称 :</label>
        <input type="text" id="name" v-model='name'>  
        <button v-on:click='handle'>提交</button>
      </div>
      <table>
        <thead>
          <tr>
            <th>编号</th>
            <th>名称</th>
            <th>时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr :key='item.id' v-for='item in books'>
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.date}}</td>
            <td>
                <!-- a标签默认有跳转行为,需要阻止 -->
              <a href="" @click.prevent='toEdit(item.id)'>修改</a>
              <span>|</span>
              <a href="" @click.prevent='deleteBook(item.id)'>删除</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      图书管理-图书列表展示功能
      注意事项:<a href="" @click.prevent>修改</a>
      事件绑定时,可以只添加修饰符,而不绑定事件函数
    */
    var vm = new Vue({
      el: '#app',
      data: {
        id: '',
        name: '',
        flag: false,
        books: [{
          id: 1,
          name: '三国演义',
          date: ''
        },{
          id: 2,
          name: '水浒传',
          date: ''
        },{
          id: 3,
          name: '红楼梦',
          date: ''
        },{
          id: 4,
          name: '西游记',
          date: ''
        }]
      },
      methods: {
            handle: function () {
                if (this.flag) {
                    // 编辑操作
                    // 就是根据当前的id去更新数组中对应的数据
                    this.books.some((item) => {
                        // 箭头函数中的this指的是定义这个函数的父级作用域中的 this
                        // 父级作用域其实就是handle的作用域,handle中的this值得就是vue实例本身,所以我们通过vue实例就可以获取到当前的id(也就是表单中的id)
                        if (item.id == this.id) {
                            item.name = this.name;
                            // 完成更新操作之后需要终止循环
                            return true;
                        }
                    });
                    this.flag = false;
                    this.id = '';
                    this.name = '';
                } else {
                    // 添加图书
                    var addBookInfo = {};
                    addBookInfo.id = this.id;
                    addBookInfo.name = this.name;
                    addBookInfo.date = '';
                    this.books.push(addBookInfo);
                    // 提交成功后将input表单清空
                    this.id = '';
                    this.name = '';
                }        
            }, 
            toEdit: function (id) {
              // 禁止修改id
              this.flag = true;
            //   console.log(id);
              // 根据id查询出要编辑的数据
              var book = this.books.filter(function(item){
                  return item.id == id;
              });
              console.log(book);
              // 把获取到的信息填充到表单
              this.id = book[0].id;
              this.name = book[0].name;
            },
            deleteBook: function (id) {
                // 删除图书
                // 根据id从数组中查找元素的索引
                // var index = this.books.findIndex(function(item){
                //     return item.id == id;
                // })
                // 根据索引删除数组元素
                // this.books.splice(index,1);

                //-------------------------------------
                // 第二种方法:(filter属于替换数组)
                this.books = this.books.filter(function(item){
                    return item.id != id;
                });   
            }
          },
              
      });
  </script>
</body>
</html>

  • 添加常用特性:
    在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    .grid {
        /* 水平居中 */
      margin: auto;
      width: 500px;
      text-align: center;
    }
    .grid .aboveTbody {
        width: 100%;
        height: 35px;
        line-height: 35px;
        text-align: center;
        background-color: orange;
        border-bottom: 1px solid greenyellow;
    }
    .grid table {
      width: 100%;
      /* 用于表格属性, 表示表格的两边框合并为一条 */
      border-collapse: collapse;
    }
    .grid th,td {
      padding: 10;
      border: 1px dashed orange;
      height: 35px;
      line-height: 35px;
    }
    .grid th {
      background-color: orange;
    }
    .grid .total {
        height: 30px;
        line-height: 30px;
        background-color: orange;
        border-bottom: 1px solid greenyellow;
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="grid">
      <h1>图书管理</h1>
      <div class="aboveTbody">
        <label for="id">编号 :</label>
        <input type="text" id="id" v-model='id' v-bind:disabled="flag" v-focus>  
        <label for="name">名称 :</label>
        <input type="text" id="name" v-model='name'>  
        <button v-on:click='handle' v-bind:disabled="submitFlag">提交</button>
      </div>
      <div class="total">
          <span>图书总数 :</span>
          <span>{{ total }}</span>
      </div>
      <table>
        <thead>
          <tr>
            <th>编号</th>
            <th>名称</th>
            <th>时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr :key='item.id' v-for='item in books'>
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.date | format('yyyy-MM-dd hh:mm:ss')}}</td>
            <td>
                <!-- a标签默认有跳转行为,需要阻止 -->
              <a href="" @click.prevent='toEdit(item.id)'>修改</a>
              <span>|</span>
              <a href="" @click.prevent='deleteBook(item.id)'>删除</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*
      图书管理-图书列表展示功能
      注意事项:<a href="" @click.prevent>修改</a>
      事件绑定时,可以只添加修饰符,而不绑定事件函数
    */

    // 过滤器:实现日期的格式处理
    Vue.filter('format', function(value, arg) {
      function dateFormat(date, format) {
          if (typeof date === "string") {
              var mts = date.match(/(\/Date\((\d+)\)\/)/);
              if (mts && mts.length >= 3) {
                  date = parseInt(mts[2]);
              }
          }
          date = new Date(date);
          if (!date || date.toUTCString() == "Invalid Date") {
              return "";
          }
          var map = {
              "M": date.getMonth() + 1, //月份 
              "d": date.getDate(), //日 
              "h": date.getHours(), //小时 
              "m": date.getMinutes(), //分 
              "s": date.getSeconds(), //秒 
              "q": Math.floor((date.getMonth() + 3) / 3), //季度 
              "S": date.getMilliseconds() //毫秒 
          };

          format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
              var v = map[t];
              if (v !== undefined) {
                  if (all.length > 1) {
                      v = '0' + v;
                      v = v.substr(v.length - 2);
                  }
                  return v;
              } else if (t === 'y') {
                  return (date.getFullYear() + '').substr(4 - all.length);
              }
              return all;
          });
          return format;
      }
      return dateFormat(value, arg);
    });

    // 自定义指令:实现获取表单焦点
    Vue.directive('focus', {
        inserted: function (el) {
            el.focus();
        }
    });

    var vm = new Vue({
      el: '#app',
      data: {
        id: '',
        name: '',
        flag: false,
        submitFlag: false,
        books: []
      },
      methods: {
            handle: function () {
                if (this.flag) {
                    // 编辑操作
                    // 就是根据当前的id去更新数组中对应的数据
                    this.books.some((item) => {
                        // 箭头函数中的this指的是定义这个函数的父级作用域中的 this
                        // 父级作用域其实就是handle的作用域,handle中的this值得就是vue实例本身,所以我们通过vue实例就可以获取到当前的id(也就是表单中的id)
                        if (item.id == this.id) {
                            item.name = this.name;
                            // 完成更新操作之后需要终止循环
                            return true;
                        }
                    });
                    this.flag = false;
                    this.id = '';
                    this.name = '';
                } else {
                    // 添加图书
                    var addBookInfo = {};
                    addBookInfo.id = this.id;
                    addBookInfo.name = this.name;
                    addBookInfo.date = '';
                    this.books.push(addBookInfo);
                    // 提交成功后将input表单清空
                    this.id = '';
                    this.name = '';
                }        
            }, 
            toEdit: function (id) {
              // 禁止修改id
              this.flag = true;
            //   console.log(id);
              // 根据id查询出要编辑的数据
              var book = this.books.filter(function(item){
                  return item.id == id;
              });
              console.log(book);
              // 把获取到的信息填充到表单
              this.id = book[0].id;
              this.name = book[0].name;
            },
            deleteBook: function (id) {
                // 删除图书
                // 根据id从数组中查找元素的索引
                // var index = this.books.findIndex(function(item){
                //     return item.id == id;
                // })
                // 根据索引删除数组元素
                // this.books.splice(index,1);

                //-------------------------------------
                // 第二种方法:(filter属于替换数组)
                this.books = this.books.filter(function(item){
                    return item.id != id;
                });   
            },
          }, 
          // 计算属性:实现统计图书数量
          computed: {
              total: function () {
                  // 计算图书的总数
                  return total = this.books.length;
              }
          },
          // 监听器:监听表单中的name,当输入的图书名称已存在时将提交按钮禁用(disabled)
          // 监听器会一直监听数据的变化,一旦变化就会触发绑定的对应的函数
          watch: {
              name: function (val) {
                  // 验证图书名称是否已经存在
                  var flag = this.books.some(function(item){
                      return item.name == val;
                  });
                  if (flag) {
                      // 图书存在
                      this.submitFlag = true;
                  } else {
                      // 图书名称不存在
                      this.submitFlag = false;
                  }
              }
          },
          // 生命周期: 图书数据处理
          mounted: function () {
              // 该生命周期钩子函数被触发时,模板已经可以使用了(可以把数据放进去了,因此我们可以从后台获取数据,把数据填充到模板中)
              // 一般此时用于获取后台数据,然后把数据填充到模板
              var data = [{
                    id: 1,
                    name: '三国演义',
                    date: 2525609999999
                    },{
                    id: 2,
                    name: '水浒传',
                    date: 2525609999999
                    },{
                    id: 3,
                    name: '红楼梦',
                    date: 2525609999999
                    },{
                    id: 4,
                    name: '西游记',
                    date: 2525609999999
                    }];
                    this.books = data;

          }
           
      });
  </script>
</body>
</html>

点击修改时:
在这里插入图片描述
编号对应的input表单不能编辑,因为设置了 disabled属性的值为true,因此可以防止编号改变。修改完成后,重新渲染列表页,同时将编号input表单的disabled属性值修改为false,且清空表单里面的内容。

输入的图书的名称已存在时,将提交表单禁用:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值