Vue初学日记Day2

Vue初学日记Day2

1.代码链接

https://github.com/dglhtao/VueLearning

2.品牌管理案例

实现品牌的添加、删除、搜索

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>2019-9-28</title>
    <script src="./lib/vue-2.4.0.js"></script>
    <link rel="stylesheet" href="./lib/bootstrap-3.3.7.css">
</head>
<body>
    <div id="app">
        
        <div class="panel panel-primary">   <!-- panel窗体控件 -->
            <div class="panel-heading">
                操作框
            </div>
            <div class="panel-body form-inline" align="center">   <!-- form-inline 元素都在一行   align="center" 内部组件居住 -->
               <label>
                   Id:
                   <input v-model="id" class="form-control" @keyup.f2="add" @keyup.13="add" v-color2="'blue'" v-fontweight="900" v-fontsize="'30px'"> 
                   <!-- 钩子函数传递参数 v-color2="'blue'",传递内容为字符串'blue',若是v-color2="blue"则会在data中寻找名为blue的变量 -->
               </label>
               <label>
                   名称:
                   <input v-model="name" class="form-control"  @keyup.13="add()">
<!-- 事件绑定机制,加()可给事件传参 -->
               </label>
               <input type="button" class="btn btn-primary" value="添加" @click="add">
               <p></p>
               <label>
                    搜索:
                    <!-- <input v-model="nameKey" id="nameKey" class="form-control" @change="search(nameKey)"> -->
                    <!-- 注意 Vue中所有指令调用时,都以v- 开头 -->
                    <input v-model="nameKey" class="form-control" @change="search(nameKey)" v-focus v-color>
                </label>
            </div>
        </div>
        
        <table class="table table-bordered table-hover" style="text-align: center">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in table" :key="index">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.time | time1}}</td>
                    <td>
                        <a href="" @click.prevent="del(item.id)">删除</a>
                    </td>
                </tr>
            </tbody>
            <!-- search方法二的表格显示方法
                <tbody>
                    <tr v-for="(item,i) in search(nameKey)" :index="i">
                        <td v-for="(val,key,index) in item" :index="i">{{val}}</td>
                        <td><a href="" @click.prevent="del(item.id)">删除</a></td>
                    </tr>
                </tbody> -->
        </table>
        
    </div>
    <script>
        Vue.filter("time1",function(time){
            var y=time.getFullYear()
            var m=time.getMonth().toString().padStart(2,'0')
            var d=time.getDate().toString().padStart(2,'0')
            var hh=time.getHours().toString().padStart(2,'0')
            var mm=time.getMinutes().toString().padStart(2,'0')
            var ss=time.getSeconds().toString().padStart(2,'0')
            // padStart padEnd
            // String.prototype.padStart(maxlength,'fillchar')
            // String.prototype.padEnd(maxlength,'fillchar')
            return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
        })
        //自定义全局按键修饰符
        Vue.config.keyCodes.f2=113

        // 自定义全局指令
        Vue.directive("focus",{
            bind:function(el){
                //注意:在每个函数中第一个永远是el,表示被绑定了指令的那个元素,这个el参数是个原生的JS对象
                // el.focus() 
                // 不能将焦点初始在el上原因:在元素绑定指令时,元素还没有被插入DOM树中,这时元素还在内存中,
                // 没有显示在页面,focus()方法没有作用,只有在元素插入到DOM中后才能获取焦点
            }, //每当指令绑定到元素上的时候,会立即执行bind函数,只执行一次
            inserted:function(el){ 
                el.focus()
                //和JS行为有关的操作,最好在inserted中去执行,放置bind,JS行为不生效
                //和样式相关的操作,一般都可以在bind执行
            }, //inserted表示元素插入到DOM中的时候(页面内容加载后),会执行inserted函数,触发一次。
            updated:function(){ }   //当VNode更新的时候(即DOM节点更新时),会执行updated,可能会触发多次
        })
        // Vue.directive() 
        // param1为指令名称,不需要加v-前缀,但在调用时必须加上v-前缀
        // param2是个对象,这个对象身上有钩子函数,这些函数可以在特定阶段,执行相关操作

        Vue.directive('color',{
            bind:function(el){
                el.style.color='red'
                //样式不必写入DOM中,可以直接写入元素属性(内存中),元素被解析入DOM中(页面中)时,样式也会被解析写入
                //样式,只要通过指令绑定给了元素,不管这个元素有没有被插入到页面中,这个元素肯定有了一个内联样式
                //浏览器的渲染引擎会解析这个样式,应用给这元素
            },
            inserted:function(el){
                el.style.color="blue"
            }
        })

        Vue.directive('color2',{
            bind:function(el,binding){
                el.style.color=binding.value
                console.log(binding.expression)
                console.log(binding.value)
                console.log(binding)
            }
        })

        var vm= new Vue({
            el:"#app",
            data:{
                id:"",
                name:"",
                nameKey:"",
                list:[
                    {id:"1",name:"奔驰",time:new Date()},
                    {id:"2",name:"宝马",time:new Date()},
                    {id:"3",name:"奥迪",time:new Date()}
                ],
                table:[]
            },
            methods:{
                add(){
                    // document.write("11")
                    if(this.id==""){
                        alert("Id should not be empty!")
                        return;
                    }
                    else
                    if(this.name==""){
                        alert("Name should not be empty!")
                        return;
                    }
                    var bool = this.list.some(item => {
                        if(item.id==this.id)
                        return true
                    });
                    console.log(bool)
                    if (bool==true)
                        alert("Id should be unique")
                    else
                    {
                        //this.ctime=new Date()
                        //var car={id:this.id, name:this.name, ctime:this.ctime}
                        //this.list.push(car)
                        this.list.push({id:this.id,name:this.name,time:new Date()})
                        this.search(this.nameKey)
                        this.id = this.name =""         /* 等号计算时从右至左 */

                        // Vue中已实现了数据的双向绑定,每当修改data,
                        // Vue会默认监听到数据改动,自动把最新数据应用到页面上
                        // Vue中,我们更多的是在对Model数据的操作,
                        // 同时,在操作Model数据的时候,指定业务逻辑
                    }
                },
                del(id){
                    // 1.如何根据id,找到要删除的那项的索引
                    /* 2.找到索引后,直接调用数组的 splice 方法
                        http://www.w3school.com.cn/jsref/jsref_splice.asp */

                        // 方法一
                        // for (let index = 0; index < this.list.length; index++) {
                        //     const element = this.list[index];
                        //     if (element.id==id) {
                        //         this.list.splice(index, 1)
                        //         break
                        //     }
                        // }

                        // 方法二
                        // this.list.some((item,i)=>{
                        //     if(item.id==id){
                        //         this.list.splice(i,1)
                        //         return true;
                        //         // some()中 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
                        //     }
                        // })
                        // (x1,x2)=>x3{} 是 function(x1,x2){return x3} 的缩写,匿名函数
                        // JS array.some()方法:https://www.runoob.com/jsref/jsref-some.html
                        
                        // 方法三
                    this.list.splice(this.list.findIndex(item=>{
                        if(item.id==id) return true
                    }),1)
                    this.search(this.nameKey)
                    // findIndex(): https://www.runoob.com/jsref/jsref-findindex.html
                },
                search(nameKey){
                    this.table=[]
                    this.list.forEach(item=>{
                        if(
                           (item.name.toString().indexOf(nameKey)!=-1))
                           this.table.push(item)
                    })
                    //search方法二,返回筛选后的数组
                    /* return this.list.filter(item=>{
                        if(item.name.includes(nameKey)) return item
                    }) */
                    // String.prototype.includes("要包含的字符串") 返回true、false
                    /* prototype 能向对象添加属性   
                         function employee(name,job,born)
                         {
                            this.name=name;
                            this.job=job;
                            this.born=born;
                         }
                         var bill=new employee("Bill Gates","Engineer",1985);
                         employee.prototype.salary=null;
                         bill.salary=20000;
                         document.write(bill.salary);
                     */
                }
            },
            filters:{
                time2(time){
                    var y=time.getFullYear()
                    var m=time.getMonth().toString().padStart(2,'0')
                    var d=time.getDate().toString().padStart(2,'0')
                    return `${y}-${m}-${d}`
                }
            },
            // 定义私有指令
            directives:{
                'fontweight':{ //设置字体粗细   
                    bind:function(el,binding){
                        el.style.fontWeight=binding.value
                    }
                },
                'fontsize': function(el,binding){ //注意:这个function等同于把代码写入bind和update中去
                    el.style.fontSize =parseInt(binding.value) + 'px'
                }
            },
            created(){
                this.table=this.list
            }
        })
        // document.getElementById("nameKey").focus() 
        // 得放最后
        // Vue不提倡对dom的操作
    </script>
</body>
</html>

3.样式

bootstrap组件查询链接:https://v3.bootcss.com/components/#panels

1)panel窗体控件

panel-primary样式

        <div class="panel panel-primary">
              <div class="panel-heading">
                    <h3 class="panel-title">Panel title</h3>
              </div>
              <div class="panel-body">
                    Panel content
              </div>
        </div>

2)输入框样式

class="form-control"

3)button样式

class="btn  btn-primary"

4)table样式

        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th>属性名</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <!-- 行 -->
                    <td>属性1</td>
                    <td>属性2</td>
                </tr>
            </tbody>
        </table>

class="table-bordered"  边框

class="table-hover" 鼠标滑过时,行变深色

4.JS中的原生对象

内置(build-in)对象是原生(native)对象的子集,前者在引擎初始化阶段就被创建好,后者包括一些在运行过程中动态创建的对象。

常用内置对象:Object、Function、Array、String、Boolean、Number、Date

使用方法参考:https://www.w3school.com.cn/jsref/index.asp

1)Array数组

属性:

length 数组长度

prototype 添加自定义属性和方法

方法:

concat(array2) 连接两个或更多数组,并返回结果

shift() 删除并返回数组第一个元素

pop() 删除并返回数组最后一个元素

unshift(item) 将参数加载到数组前面,返回数组长度

push(item) 将参数加载到数组后面,返回数组长度

splice(start, deleteCount, val1, val2, ...) 从start位置开始删除deleteCount项,并从该位置起插入val1, val2, ...

reverse() 将数组反序,并返回新的数组

slice(start, end) 返回从原数组指定起始终止下标之间组成的新数组

sort() 对数组元素进行排序,并返回

2)String字符串

属性:

length 字符串长度

prototype 添加自定义属性和方法

方法:

charAt(index) 返回指定位置的字符

charCodeAt(index) 返回指定位置字符的Unicode编码

concat(str2) 连接字符串,并返回

fontcolor(“Red”) 使用指定颜色来显示字符串

fontsize(size) 使用指定大小来显示字符串,size为1至7的数字

fromCharCode(code) 从字符编码创建一个字符串

indexOf(searchValue,fromIndex) 检索字符串,从第fromIndex位置开始搜索searchValue首次出现的位置,无fromIndex则从首位开始。返回首次出现的位置或-1。(注:indexOf对大小写敏感)

italics() 使用斜体显示字符串

replace(a,b) 用b替换a

slice(start,end) 截取片段

toLowerCase() 转换为小写

toUpperCase() 转换为大写

valueOf() 返回某个字符对象数值

3)Boolean对象

prototype

toString()

valueOf()

4)Number对象

创建:

var myNum=new Number(value);
var myNum=Number(value);

属性:

MAX_VALUE 可表示的最大的数

MIN_VALUE 可表示的最小的数

NEGATIVE_INFINITY 负无穷大,溢出时返回的值

POSITIVE_INFINITY 正无穷大,溢出时返回的值

NaN 非数字时返回的值

prototype

方法:

toString()

toLocaleString() 把数字转换为字符串,使用本地数字格式顺序

toFixed(num) 把数字四舍五入转化为指定小数位的数字字符串

toExponential(num) 小数点之后有num位数字,不足时补0,省略则保留尽可能多位

5)Date对象

方法:

Date() 返回当日的日期和时间

getFullYear()

getMonth()

getDate()

getDay()

getHours()

getMinutes()

getSeconds()

getMilliseconds()

获取年 月(0~11) 日(1~31) 星期(0~6) 小时 分钟 秒 毫秒

getTime() 获取1970.1.1至今的毫秒数

parse(dateString) 获取1970.1.1至指定字符串日期的毫秒数

setFullYear() 

setMonth()

setDate()

setHours()

setMinutes()

setSeconds()

setMillisenconds()

setTime()

date变量设置年 月 日 时 分 秒 毫秒 从1970.1.1开始的毫秒数

toString()

toTimeString() 时间部分转换为字符串

toDateString() 日期部分转换为字符串

5、Array.

foreach

map

filter

some

every

find

reduce()

reduceRight()

indexOf()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值