【编程鹿】学Vue.js这一篇就够了「万字学会|通俗易懂」下篇

1540394364528
1540394364528

路由vue-router

场景模拟

现在我们来实现这样一个功能:

一个页面,包含登录和注册,点击不同按钮,实现登录和注册页切换。

编写父组件

为了让接下来的功能比较清晰,我们先新建一个文件夹:src

然后新建一个HTML文件,作为入口:index.html

然后编写页面的基本结构:

<div id="app">
    <span>登录</span>
    <span>注册</span>
    <hr/>
    <div>
        登录页/注册页
    </div>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el:"#app"
    })
</script>

编写登录及注册组件

接下来我们来实现登录组件,以前我们都是写在一个文件中,但是为了复用性,开发中都会把组件放入独立的JS文件中,我们新建一个user目录以及login.js及register.js。

编写组件,这里我们只写模板,不写功能。

login.js内容如下:

const loginForm = {
    template:'\
    <div>\
    <h2>登录页</h2> \
    用户名:<input type="text"><br/>\
    密码:<input type="password"><br/>\
    </div>\
    '

}

register.js内容:

const registerForm = {
    template:'\
    <div>\
    <h2>注册页</h2> \
    用&ensp;户&ensp;名:<input type="text"><br/>\
    密&emsp;&emsp;码:<input type="password"><br/>\
    确认密码:<input type="password"><br/>\
    </div>\
    '

}

在父组件中引用

<div id="app">
    <span>登录</span>
    <span>注册</span>
    <hr/>
    <div>
        <!--<loginForm></loginForm>-->
        <!--
            疑问:为什么不采用上面的写法?
            由于html是大小写不敏感的,如果采用上面的写法,则被认为是<loginform></loginform>
            所以,如果是驼峰形式的组件,需要把驼峰转化为“-”的形式
         -->

        <login-form></login-form>
        <register-form></register-form>
    </div>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script src="user/login.js"></script>
<script src="user/register.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el"#app",
        components: {
            loginForm,
            registerForm
        }
    })
</script>

问题

我们期待的是,当点击登录或注册按钮,分别显示登录页或注册页,而不是一起显示。

但是,如何才能动态加载组件,实现组件切换呢?

虽然使用原生的Html5和JS也能实现,但是官方推荐我们使用vue-router模块。

vue-router简介和安装

使用vue-router和vue可以非常方便的实现 复杂单页应用的动态路由功能。

官网:https://router.vuejs.org/zh-cn/

使用npm安装:npm install vue-router --save

在index.html中引入依赖:

<script src="../node_modules/vue-router/dist/vue-router.js"></script>

快速入门

新建vue-router对象,并且指定路由规则:

// 创建VueRouter对象
const router = new VueRouter({
    routes:[ // 编写路由规则
        {
            path:"/login"// 请求路径
            component:loginForm // 组件名称
        },
        {path:"/register",component:registerForm},
    ]
})
  • 创建VueRouter对象,并指定路由参数
  • routes:路由规则的数组,可以指定多个对象,每个对象是一条路由规则,包含以下属性:
    • path:路由的路径
    • component:组件名称

在父组件中引入router对象:

var vm = new Vue({
    el:"#app",
    components:{// 引用登录和注册组件
        loginForm,
        registerForm
    },
    router // 引用上面定义的router对象
})

页面跳转控制:

<div id="app">
    <!--router-link来指定跳转的路径-->
    <span><router-link to="/login">登录</router-link></span>
    <span><router-link to="/register">注册</router-link></span>
    <hr/>
    <div>
        <!--vue-router的锚点-->
        <router-view></router-view>
    </div>
</div>
  • 通过 router-view 来指定一个锚点,当路由的路径匹配时,vue-router会自动把对应组件放到锚点位置进行渲染
  • 通过 router-link 指定一个跳转链接,当点击时,会触发vue-router的路由功能。

单文件组件

vue-cli3开发单文件组件

Vue.component('组件名',{

})
new Vue({})

缺点

  • 全局定义组件的名字时不能重复
  • 字符串模板 es6提供了模板字符串 \
  • 不支持css

在vue中把.vue的文件称为 单文件组件

Vue CLI3 脚手架

基本配置

  • 安装Nodejs
    • 保证Node.js8.9或更高版本
    • 终端中输入node -v,保证已安装成功
  • 安装淘宝镜像源
    • npm install -g cnpm --registry=https://registry.npm.taobao.org
    • 以后的npm可以用cnpm代替
  • 安装Vue Cli3脚手架
    • cnpm install -g @vue/cli
  • 检查其版本是否正确
    • vue --version

快速原型开发

在命令行工具cmd,或者Intellij IDEA的Terminal中进入想要构建项目的目录,输入

vue init webpack project-name

回车,webpack默认版本为2.0。

接下来会出现几个提示,分别是输入项目名称、描述、作者等,按实际情况选择即可。

?Project name ---- 项目名称,init命令时也填了个project-name,如果无需更改,直接回车即可;

?Project description ---- 项目描述,按需填写。无需填写可以直接回车;

?Author ---- 作者

?Vue build ---- 构建模式,一般默认第一个;

?Install vue-router? ---- 是否安装vue-router。选Y。后边构建项目会用到。

?Use ESLint to lint yout code? ---- 格式校验,按需;

?Set up unit tests ---- 测试相关,按需;

?Setup e2e tests with Nightwatch? ---- 测试相关,按需;

?Should we run ‘npm install’ for you after the project has been created? ---- 按需,这里我选Yes, use NPM。如果选No,后续自己在目标

目录下执行npm install即可。这样构建出来的项目,可以直接运行。进入项目所在目录,执行npm run dev,执行完看到以下提示:

Your application is running here: http://localhost:8080

在浏览器打开http://localhost:8080,看到这个页面,接下来就可以开始开发了。

分析Vue脚手架生成的项目结构

​ node_modules:依赖包目录 ​ public:静态资源目录 ​ src:源码目录 ​ src/assets:资源目录 ​ src/components:组件目录 ​ src/views:视图组件目录 ​ src/App.vue:根组件 ​ src/main.js:入口js ​ src/router.js:路由js ​ babel.config.js:babel配置文件

使用单文件组件开发购物车

<template>
  <div id="app">
    <h1>{{title}}</h1>
    <ul>
      <li v-for="item in cartList" :key="item.id">
        <h2>{{item.title}}</h2>
        <p>${{item.price}}</p>
      </li>
    </ul>
    <my-cart :title="title" :cart-list="cartList"></my-cart>
  </div>
</template>

  <script>
    import  MyCart from './components/Cart';
    export default {
      name:"app",
      data() {
        return {
          cartList:[
            {id:1,title:"vue实战",price:188,active:true,count:2},
            {id:2,title:"react实战",price:288,active:false,count:1}],
          title:"购物车"
        };
      },
      components:{MyCart}
    }
  
</script>

购物车文件代码:

<template>
    <div>
      <h1>{{title}}</h1>
      <table border="1">
        <tr>
          <th>#</th>
          <th>课程</th>
          <th>单价</th>
          <th>数量</th>
          <th>总价</th>
        </tr>
        <tr v-for="(c,index) in cartList" :key="c.id">
          <td>
            <input type="checkbox" v-model="c.active">
          </td>
          <td>{{c.title}}</td>
          <td>{{c.price}}</td>
          <td>
            <button @click="substract(index)">-</button>
            {{c.count}}
            <button @click="add(index)">+</button>
          </td>
          <td>¥{{c.price*c.count}}</td>
        </tr>
        <tr>
          <td></td>
          <td colspan="2">{{activeCount}}/{{count}}</td>
          <td colspan="2">¥{{total}}</td>
        </tr>
      </table>
    </div>
</template>

<script>
    export default {
      name:"cart",
      props:['title','cartList'],
      methods: {
        remove(i) {
          if (window.confirm("确定是否要删除?")) {
            this.cartList.splice(i, 1);
          }
        },
        substract(i) {
          let count = this.cartList[i].count;
          count > 1 ? (this.cartList[i].count -= 1) : this.remove(i);
        },
        add(i) {
          this.cartList[i].count++;
        }
      },
      computed:{
        count(){
          return this.cartList.length;
        },
        activeCount(){
          return this.cartList.filter(v=>v.active).length;
        },
        total(){
          let sum=0;
          this.cartList.forEach(c=>{
            if(c.active){
              sum+=c.price*c.count;
            }
          });
          return sum;
        }
      }
    }
</script>


<style scoped>

</style>

Vuejs Ajax

Vuejs 并没有直接处理ajax的组件,但可以使用axios组件实现对异步请求的操作。

Axios简介

# 如果使用npm则可以如下安装
npm install axios

axios应用

方法说明

axios可以使用的方法有:

  • axios(config)

config请求配置

这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method ,请求将默认使用 get 方法

{
 // `url` 是用于请求的服务器 URL
 url: '/user',
 
 // `method` 是创建请求时使用的方法
 method: 'get'// 默认是 get
 
 // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
 // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
 baseURL: 'https://some-domain.com/api/',
 
 // `params` 是即将与请求一起发送的 URL 参数
 // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
 params: {
  ID: 12345
 },
 
 // `data` 是作为请求主体被发送的数据
 // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
 // 在没有设置 `transformRequest` 时,必须是以下类型之一:
 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
 // - 浏览器专属:FormData, File, Blob
 // - Node 专属: Stream
 data: {
  firstName: 'Fred'
 },
 
 // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
 // 如果请求话费了超过 `timeout` 的时间,请求将被中断
 timeout: 1000
}

响应结构

{
 // `data` 由服务器提供的响应
 data: {},
 
 // `status` 来自服务器响应的 HTTP 状态码
 status: 200,
 
 // `statusText` 来自服务器响应的 HTTP 状态信息
 statusText: 'OK',
 
 // `headers` 服务器响应的头
 headers: {},
 
 // `config` 是为请求提供的配置信息
 config: {}
}

axios方法示例

可以通过向 axios 传递相关配置来创建请求

axios(config)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vuejs测试</title>
    <script src="node_modules/vue/dist/vue.js"></script>
    <script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
    <ul>
        <li v-for="(user,index) in users" :key="index">
            {{index}} -- {{user.name}} -- {{user.age}} -- {{user.gender}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    var app = new Vue({
        el"#app",
        data: {
            users: []
        },
        created() {
            // 初始化加载数据
            axios({
                method"get",
                url"data.json"
            }).then((res) => {
                console.log(res);
                // 将获取数据设置到users属性
                // 不能使用this,在axios回调函数中表示窗口,不是vue实例
                app.users = res.data;
            }).catch(error => {
                alert(error);
            })
        }
    });
</script>
</body>
</html>

综合案例

购物车综合案例

第一步:实现图书的列表显示

<body>
    <div id="myDiv">
        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="book in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>{{book.price}}</td>
                <td>
                    <button>-</button>
                    {{book.number}}
                    <button>+</button>
                </td>
                <td>
                    <button>删除</button>
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                books: [
                    {id1name'天龙八部'pubDate:'1988-02' ,price80.00number1},
                    {id2name'射雕英雄传'pubDate:'2000-09'price20.00number1},
                    {id3name'倚天屠龙记'pubDate:'1986-12'price60.00number1},
                    {id4name'鹿鼎记'pubDate:'2001-05'price70.00number1}
                ]
            }
        });
    
</script>
</body>

第二步:价格小数问题处理

方式一:methods

<body>
    <div id="myDiv">
        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="book in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>{{getPrice(book.price)}}</td>
                <td>
                    <button>-</button>
                    {{book.number}}
                    <button>+</button>
                </td>
                <td>
                    <button>删除</button>
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                books: [
                    {id1name'天龙八部'pubDate:'1988-02' ,price80.01number1},
                    {id2name'射雕英雄传'pubDate:'2000-09'price20.00number1},
                    {id3name'倚天屠龙记'pubDate:'1986-12'price60.00number1},
                    {id4name'鹿鼎记'pubDate:'2001-05'price70.00number1}
                ]
            },
            methods: {
                getPrice(price){
                    return '¥' + price.toFixed(2);
                }
            }
        });
    
</script>
</body>

方式二:过滤器

==可以应用到插值表达式或v-bind表达式中,可以做格式化。==
<body>
    <div id="myDiv">
        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="book in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>{{book.price | getPrice}}</td>
                <td>
                    <button>-</button>
                    {{book.number}}
                    <button>+</button>
                </td>
                <td>
                    <button>删除</button>
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                books: [
                    {id1name'天龙八部'pubDate:'1988-02' ,price80.01number1},
                    {id2name'射雕英雄传'pubDate:'2000-09'price20.00number1},
                    {id3name'倚天屠龙记'pubDate:'1986-12'price60.00number1},
                    {id4name'鹿鼎记'pubDate:'2001-05'price70.00number1}
                ]
            },
            filters: {
                getPrice(price){
                    return '¥' + price.toFixed(2);
                }
            }
        });
    
</script>
</body>

第三步:数量加减操作

<body>
    <div id="myDiv">
        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="book in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>{{book.price}}</td>
                <td>
                    <button @click="decrement(book)" v-bind:disabled="book.number < 2">
                      -
                   </button>
                    {{book.number}}
                    <button @click="increment(book)">+</button>
                </td>
                <td>
                    <button>删除</button>
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                books: [
                    {id1name'天龙八部'pubDate:'1988-02' ,price80.01number1},
                    {id2name'射雕英雄传'pubDate:'2000-09'price20.00number1},
                    {id3name'倚天屠龙记'pubDate:'1986-12'price60.00number1},
                    {id4name'鹿鼎记'pubDate:'2001-05'price70.00number1}
                ]
            },
            methods: {
                decrement(book){
                    book.number--;
                },
                increment(book){
                    book.number++;
                }
            }
        });
    
</script>
</body>

第四步:移除按钮

<body>
    <div id="myDiv">
        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="(book,index) in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>{{book.price}}</td>
                <td>
                    <button @click="decrement(book)" v-bind:disabled="book.number < 2">-</button>
                    {{book.number}}
                    <button @click="increment(book)">+</button>
                </td>
                <td>
                    <button @click="deleteHandle(index)">删除</button>
                </td>
            </tr>
        </table>
        <h2 v-if="books.length <= 0">
            购物车空空如也
        </h2>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                books: [
                    {id1name'天龙八部'pubDate:'1988-02' ,price80.01number1},
                    {id2name'射雕英雄传'pubDate:'2000-09'price20.00number1},
                    {id3name'倚天屠龙记'pubDate:'1986-12'price60.00number1},
                    {id4name'鹿鼎记'pubDate:'2001-05'price70.00number1}
                ]
            },
            methods: {
                deleteHandle(index){
                    this.books.splice(index,1);
                }
            }
        });
    
</script>
</body>

第五步:计算最终价格

<body>
    <div id="myDiv">
        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="(book,index) in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>{{book.price}}</td>
                <td>
                    <button @click="decrement(book)" v-bind:disabled="book.number < 2">-</button>
                    {{book.number}}
                    <button @click="increment(book)">+</button>
                </td>
                <td>
                    <button @click="deleteHandle(index)">删除</button>
                </td>
            </tr>
        </table>
        <h1>总价:{{totalPrice | getPrice}}</h1>
        <h2 v-if="books.length <= 0">
            购物车空空如也
        </h2>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                books: [
                    {id1name'天龙八部'pubDate:'1988-02' ,price80.01number1},
                    {id2name'射雕英雄传'pubDate:'2000-09'price20.00number1},
                    {id3name'倚天屠龙记'pubDate:'1986-12'price60.00number1},
                    {id4name'鹿鼎记'pubDate:'2001-05'price70.00number1}
                ]
            },
            filters: {
                getPrice(price){
                    return '¥' + price.toFixed(2);
                }
            },
            computed: {
                totalPrice(){
                    return this.books.reduce((sum,book)=>{
                        return sum  + book.price;
                    },0)
                }
            }
        });
    
</script>
</body>

图书管理综合案例

第一步:实现列表、新增和删除

<body>
    <div id="myDiv">
        id: <input type="text" v-model="id"/>
        图书名称: <input type="text" v-model="name"/>
        <button @click="add">添加</button>
        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>操作</td>
            </tr>
            <tr v-for="(book,index) in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>
                    <a href="" @click.prevent="deleteHandle(index)">删除</a> //阻止事件默认行为
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                id'',
                name'',
                books: [
                    {id1name'天龙八部'pubDatenew Date()},
                    {id2name'射雕英雄传'pubDatenew Date()},
                ]
            },
            methods: {
                add(){
                    let book = {id:this.id, name:this.name , pubDate:new Date()};
                    this.books.push(book);
                },
                deleteHandle(index){
                    this.books.splice(index,1);
                }
            }
        });
    
</script>
</body>

第二步:实现搜索筛选

<body>
    <div id="myDiv">
        id: <input type="text" v-model="id"/>
        图书名称: <input type="text" v-model="name"/>
        <button @click="add">添加</button>

        根据图书名称搜索:<input type="text" v-model="kw"/>

        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>操作</td>
            </tr>
            <tr v-for="(book,index) in search(kw)">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>
                    <a href="" @click.prevent="deleteHandle(index)">删除</a>
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                id'',
                name'',
                kw'',
                books: [
                    {id1name'天龙八部'pubDatenew Date()},
                    {id2name'射雕英雄传'pubDatenew Date()},
                ]
            },
            methods: {
                add(){
                    let book = {id:this.id, name:this.name , pubDate:new Date()};
                    this.books.push(book);
                },
                search(kw){
                    let result = [];
                    this.books.forEach((item)=>{
                        if (item.name.includes(kw)){
                            result.push(item);
                        }
                    });
                    return result;
                }
            }
        });
    
</script>
</body>
==换种方式实现:==
search(kw){
    return this.books.filter((item)=>{
        return item.name.includes(kw);
    })
}

第三步:日期格式化

<body>
    <div id="myDiv">
        id: <input type="text" v-model="id"/>
        图书名称: <input type="text" v-model="name"/>
        <button>添加</button>

        根据图书名称搜索:<input type="text" v-model="kw"/>

        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>操作</td>
            </tr>
            <tr v-for="(book,index) in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate | dateFormat}}</td>
                <td>
                    <a href="">删除</a>
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script src="../js/moment.js"></script>
    <script type="text/javascript">
        Vue.filter("dateFormat",(value)=>{
            return moment(value).format("YYYY-MM-DD");
        });
        const app = new Vue({
            el"#myDiv",
            data: {
                id'',
                name'',
                kw'',
                books: [
                    {id1name'天龙八部'pubDatenew Date()},
                    {id2name'射雕英雄传'pubDatenew Date()},
                ]
            }
        });
    
</script>
</body>

第四步:优化添加功能

==需求:上面的案例中,我们需要点击添加按钮实现添加一本书,有时候是这样子的,我们按下回车键也可以添加,下面就来做这个功能。==

按下enter键实现添加方式1

图书名称: <input type="text" v-model="name" @keyup.enter="add"/>  // 可行

按下enter键实现添加方式2

图书名称: <input type="text" v-model="name" @keyup.13="add"/>  // 键码可行

按下F2键实现添加方式1

图书名称: <input type="text" v-model="name" @keyup.f2="add"/> // 可行,低版本不可行

按下F2键实现添加方式2

图书名称: <input type="text" v-model="name" @keyup.113="add"/> // 可行,通过键码代表F2可行

按下F2键盘实现添加方式3

==通过键码代表F2可行,但是阅读性不好,可以自定义按键修饰符,主要是处理低版本Vue的问题。==

图书名称: <input type="text" v-model="name" @keyup.f2="add"/>
Vue.config.keyCodes.f2 = 113

第五步:页面打开的时候就搜索框获得焦点

根据图书名称搜索:<input type="text" v-model="kw" v-focus/>
Vue.directive("focus",{
    inserted: function(el){
        el.focus();
    }
});

第五步:实现修改功能

<body>
    <div id="myDiv">
        id: <input type="text" v-model="id" :disabled="disable"/>
        图书名称: <input type="text" v-model="name"/>
        <button @click="handle">提交</button>

        根据图书名称搜索:<input type="text" v-model="kw"/>

        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>操作</td>
            </tr>
            <tr v-for="(book,index) in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>
                    <a href="" @click.prevent="update(book.id)">修改</a>
                    <a href="">删除</a>
                </td>
            </tr>
        </table>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                id'',
                name'',
                kw'',
                disablefalse,
                books: [
                    {id1name'天龙八部'pubDatenew Date()},
                    {id2name'射雕英雄传'pubDatenew Date()},
                ]
            },
            methods: {
                // 添加和修改重用
                handle(){
                    if(this.disable){
                        // 为true,就表示修改
                        this.books.forEach((item)=>{
                            if(item.id == this.id){
                                item.name = this.name;
                                return item;
                            }
                        });
                        // 修改完毕之后还需要对disable设置为true表示允许添加
                        this.disable = false;
                        this.id = "";
                        this.name = "";
                    }else{
                        // 就表示添加
                        let book = {id:this.id, name:this.name , pubDate:new Date()};
                        this.books.push(book);
                    }
                },
                update(bookId){
                    // 0、禁止修改id文本框
                    this.disable = true;

                    // 1、根据bookId查找出要编辑的图书
                    let book = this.books.filter((item)=>{
                        return item.id == bookId;
                    });
                    // 2、把获取到的图书填充到表单中
                    this.id = book[0].id;
                    this.name = book[0].name;
                }
            }
        });
    
</script>
</body>

第六步:使用计算属性统计图书种类

<h1>总共有{{totalCount}}种不同种类的书</h1>
computed: {
    totalCount(){
        return this.books.length;
    }
}

第七步:不能添加重复的图书【监听器】

<body>
    <div id="myDiv">
        id: <input type="text" v-model="id" :disabled="disable"/>
        图书名称: <input type="text" v-model="name"/>
        <button @click="handle" :disabled="flag">提交</button>

        根据图书名称搜索:<input type="text" v-model="kw"/>

        <table border="1">
            <tr>
                <td>图书编号</td>
                <td>图书名称</td>
                <td>出版日期</td>
                <td>操作</td>
            </tr>
            <tr v-for="(book,index) in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.pubDate}}</td>
                <td>
                    <a href="" @click.prevent="update(book.id)">修改</a>
                    <a href="">删除</a>
                </td>
            </tr>
        </table>
        <h1>总共有{{totalCount}}种不同种类的书</h1>
    </div>
    <script src="../js/vue.js"></script>
    <script type="text/javascript">
        const app = new Vue({
            el"#myDiv",
            data: {
                id'',
                name'',
                kw'',
                disablefalse,
                flagfalse,
                books: [
                    {id1name'天龙八部'pubDatenew Date()},
                    {id2name'射雕英雄传'pubDatenew Date()},
                ]
            },
            computed: {
                totalCount(){
                    return this.books.length;
                }
            },
            methods: {
                // 添加和修改重用
                handle(){
                    if(this.disable){
                        // 为true,就表示修改
                        this.books.forEach((item)=>{
                            if(item.id == this.id){
                                item.name = this.name;
                                return item;
                            }
                        });
                        // 修改完毕之后还需要对disable设置为true表示允许添加
                        this.disable = false;
                        this.id = "";
                        this.name = "";
                    }else{
                        // 就表示添加
                        let book = {id:this.id, name:this.name , pubDate:new Date()};
                        this.books.push(book);
                    }
                },
                update(bookId){
                    // 0、禁止修改id文本框
                    this.disable = true;

                    // 1、根据bookId查找出要编辑的图书
                    let book = this.books.filter((item)=>{
                        return item.id == bookId;
                    });
                    // 2、把获取到的图书填充到表单中
                    this.id = book[0].id;
                    this.name = book[0].name;
                }
            },
            watch:{
                name(value){
                    let result = false;
                    this.books.forEach((item)=>{
                        if (item.name == value){
                            result = true;
                            return;
                        }
                    })
                    if (result){
                        console.log("11");
                        this.flag = true;
                    }else{
                        this.flag = false;
                    }
                }
            }
        });
    
</script>
</body>

第八步:图书数据的初始化

mounted(){
    // 模拟ajax请求获取数据
    let result = [
                {id1name'天龙八部'pubDatenew Date()},
                {id2name'射雕英雄传'pubDatenew Date()}
                ];

    this.books = result;
},

❤️ 帅气的你又来看了我

如果你觉得这篇内容对你挺有有帮助的话:

  1. 点赞支持下吧,让更多的人也能看到这篇内容(收藏不点赞,都是耍流氓 -_-)

  2. 欢迎在留言区与我分享你的想法,也欢迎你在留言区记录你的思考过程。

  3. 觉得不错的话,也可以关注 编程鹿 的个人公众号看更多文章和讲解视频(感谢大家的鼓励与支持🌹🌹🌹)

posted @ 2020-11-20 17:04  编程鹿  阅读(162)  评论(0编辑  收藏  举报