vue实现图书的添加删除

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="./js/vue.js"></script>
</head>

<body>
    <div id="app" class="container">
        <h3 class="text-center text-info">图书管理</h3>
        <div class="form-group">
            <input id="my-input" class="form-control" type="text" placeholder="请输入图书名称" v-model="kw"
                @keydown.enter="enter">
        </div>
        <hr>
        <table class="table table-light table-bordered">
            <tbody>
                <tr>
                    <th>id</th>
                    <th>书名</th>
                    <th>添加时间</th>
                    <th>操作</th>
                </tr>
                <!-- 3.遍历数据  -->
                <tr v-for="(item,index) in arr" :key="item.id">
                    <td>{
         
  {item.id}}</td>
                    <td>{
         
  {item.name}}</td>
                    <td>{
         
  {item.time}}</td>
                    <td>
                        <button class="btn btn-danger" @click="arr.splice(index,1)">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <script>
        // 100000-999999
        var vm = new Vue({
            el: "#app",
            data: {
                // 1.输入框的内容
                kw: "",
                // 2.列表数据 
                arr: [{
                    id: "1",
                    name: "三国演义",
                    time: "2021/1/28"
                }]
            },
            methods: {
                // 4.按了回车
                enter() {
                    if (this.kw === ) {
                        alert("图书名称不能为空")
                        return;
                    }
                    /*this.arr.push({
                        id:new Date().getTime()++Math.floor(Math.random()*(999999-100000)+100000),
                        name:this.kw,
                        time:new Date().toLocaleDateString()
                    })*/

                    this.arr = [{
                        id: new Date().getTime() +  + Math.floor(Math.random() * (999999 - 100000) +
                            100000),
                        name: this.kw,
                        time: new Date().toLocaleDateString()
                    }, ...this.arr, ]
                    this.kw = "";
                }
            }
        })
    </script>
</body>

</html>
经验分享 程序员 微信小程序 职场和发展