Vue进阶

教学计划

1.上次vue基础回顾

2.作业问题

(1) 品牌列表 -搜索

  <table border="1" align="left" width="60%"
            class="table table-bordered table-condensed table-striped table-responsive table-hover">
            <tr align="center">
                <td><input type="checkbox" id="selectAll"></td>
                <td>序号</td>
                <td>品牌</td>
                <td>创建时间</td>
                <td>操作</td>
            </tr>
            <!-- searchByKeyWords函数调用时,加载时调用一次,如果keywods属性数据发生变化,则此函数会被再次触发 -->
            <tr align="center" v-for="(car,index) in searchByKeywords(keywords)">
                <td><input type="checkbox" :id="car.id"></td>
                <td>{{index+1}}</td>
                <td>{{car.name}}</td>
                <td>{{car.ctime}}</td>
                <td><a href="#">删除</a></td>
            </tr>
        </table>

<script>
        //创建VM对象 
        var vm = new Vue({
            el: "#app",
            data: {
                id:4,
                name:"",
                keywords:"",
                list:[
                    {id:1,name:"BMW",ctime:new Date()},
                    {id:2,name:"Benz",ctime:new Date()},
                    {id:3,name:"Buick",ctime:new Date()},
                    {id:4,name:"Honda",ctime:new Date()}
                ]
            },
            methods: {
                add(){
                     //获取双向绑定的数据
                     let car = {id:++this.id,name:this.name,ctime:new Date()};
                     this.list.push(car);
                },
                searchByKeywords(keywords){
                    //获取keywords  ES6 - let
                     //this.list
                    //  for(let i=0;i<this.list.length;i++){
                    //  }

                    // for(car of this.list){
                    //     console.log(car.name);
                    // }

                    //ES6 - 高阶函数
                    // this.list.forEach(function(obj){
                    //     console.log(obj.id+","+obj.name);
                    // });
                    let newList = [];
                    //ES6 - 箭头函数
                    this.list.forEach(obj=>{
                        //console.log(obj.id+","+obj.name);
                        if(obj.name.indexOf(keywords) !=-1){
                            newList.push(obj);
                        }
                    });

                    //es6-->filter函数
                    return newList;
                }
            }
        });
    </script>

删除功能:

  <!-- searchByKeyWords函数调用时,加载时调用一次,如果keywods属性数据发生变化,则此函数会被再次触发 -->
<tr align="center" v-for="(car,index) in searchByKeywords(keywords)" :key="car.id">
    <td><input type="checkbox" :id="car.id"></td>
    <td>{{index+1}}</td>
    <td>{{car.name}}</td>
    <td>{{car.ctime}}</td>
    <td><a href="javascript:void(0);" @click.prevent="del(index)">删除</a></td>
</tr>


del(i){
	//this.list.splice(index,个数)
	this.list.splice(i,1);
}

(2) Vue样式练习:

<body>
    <div id="app">
        <span @click="f('red')">红色</span> | 
        <span @click="f('yellow')">黄色</span> | 
        <span @click="f('blue')">蓝色</span> 
        <br><br>
        <div :style="{width:'150px',height:'150px',backgroundColor:bg}">

        </div>
    </div>


    <script>
      //创建VM对象 
        var vm = new Vue({
           el: "#app", 
           data:{   
               bg:'red'
           },
           methods:{ 
               f(color){
                    this.bg = color;
               }    
           }
        });
    </script>
</body>

3.过滤器

  • 作用: Filter -对我们常见的文本格式化
  • 使用的位置: 插件表达式{{}} , v-bind=""
  • 分类 : 局部和全局
    • 局部过滤器只能在当前所定义的vue实例中使用 new Vue({data,methods,filters:})
    • 全局过滤器可以用于多个vue实例 - Vue.filter()
  • 过滤器的注册与使用:
    • 过滤器的名字: (要过滤的数据)=>{return 过滤的结果}
    • 在视图中使用过滤器: {{被过滤的数据 | 过滤器的名字}} --管道符
  • 过滤可以串联使用: {{被过滤的数据 | 过滤器1 |过滤器2|}}
  • 当全局过滤器与局部过滤器同名时,局部优先
 //全局过滤器
        // Vue.filter("过滤名",{
                //  执行的过滤操作;
                //  return 过滤后的结果;
        // });

        Vue.filter("dateConverter",(val,pattern)=>{
            var d = new Date(val); //将参数字符串格式化成一个日期对象
                    var year = d.getFullYear();
                    var month = d.getMonth()+1;
                    var day = d.getDate();
                    
                    if(pattern.toLowerCase()=='yyyy-mm-dd'){
                        return year+"-"+month+"-"+day; 
                    }else if(pattern.toLowerCase()=='yyyy-mm-dd hh:mm:ss'){
                        var d = new Date(val); //将参数字符串格式化成一个日期对象
                        var hh = d.getHours();
                        var mm = d.getMinutes();
                        var ss = d.getSeconds();    
                        //拼接字符串 在 ES6建议使用模板字符串
                        //return year+"-"+month+"-"+day+" "+hh+":"+mm+":"+ss; 
                        return `${year}-${month}-${day} ${hh}:${mm}:${ss}`;                    
                    }else{
                        return "date format error!";
                    }
        })

4.键盘修饰符 & Vue自定义指令 [了解]

4-1.键盘修饰符

  • 允许在键盘按键事件发生时,添加修饰符,关注按键细节
<label>
    品牌:<input type="text" class="form-control" v-model="name" @keyup.enter="add()"/>
 </label>
  • 也可以支持按键码

    @keyup.13=“add()” 13按键虚拟码

  • 自定义键盘修饰符

    • 实现上述按键的功能,可以定义键盘上任意按键来触发事件
//自定义键盘修饰符 aa  等于的值为按键虚拟码
Vue.config.keyCodes.aa= 113 //113对应的键是F2

<input type="text" class="form-control" v-model="name" @keyup.aa="add()"/>

4-2.自定义指令 directive

  • 内置指令 v-text,v-html,v-bind,v-model
  • 自定义指令:对普通 DOM 元素进行底层操作,这时候就会用到自定义指令
  • v-自定义指令名
  • 分为全局与局部注册
 //自定义全局指令
        Vue.directive("focus",{
            //钩子函数 Hook 
            inserted:function(el){  //此时的形参表示的是应用此指令元素 element - 
                el.focus(); //系统的聚焦
            }

        });  


//局部指令
directives:{
                "color":{
                    //el表示当前元素  ,binding封装了为元素赋值对象
                    bind(el,binding){
                        // console.log(el);
                        // console.log(binding);
                        el.style.color=binding.value;
                    }
                },
                "font-weight":{
                    bind(el,binding){
                        el.style.fontWeight=binding.value;
                    }
                }
            }

5.Vue生命周期LifeCycle - 钩子函数

  • 创建期间-生命周期函数 [钩子函数]
    • beforeCreated
    • created
    • beforeMount
    • mounted
  • 运行期间 - 生命周期函数 [钩子函数]
    • beforeUpdate
    • updated
  • 销毁期间 - 生命周期函数 [钩子函数]
    • beforeDestory
    • destoryed
<body>
    <div id="app">
        <p id="p1">{{msg}}</p>
        <button type="button" @click="msg='world'">更新数据</button>
    </div>


    <script>
      //创建VM对象 
        var vm = new Vue({
           el: "#app", 
           data:{ 
               msg:'hello',
               list:[]
           },
           methods:{ 
               print(){
                   console.log("print()...");
               }
           },
           beforeCreate(){  //实例刚在内存中被创建出来,此时,还没有初始化好 data 和 methods 属性
             console.log("beforeCreate()....");
             console.log(this.msg); //undefined 
             //this.print();
           },
           created(){  //实例已经在内存中创建OK,此时 data 和 methods 已经创建OK,此时还没有开始 编译模板
              console.log("created()....");
              console.log(this.msg); //undefined 
              //this.print();
           },
           /内存中进行vue的指令编译,运行,生成VDOM
           beforeMount() {
               console.log("beforeMount...");
               console.log(this.msg); 
               let p = document.getElementById("p1").innerText;
               console.log(p);
           },
           mounted(){
               console.log("mounted....");
               console.log(this.msg); 
               let p = document.getElementById("p1").innerText;
               console.log(p);
           },
           
           beforeUpdate(){
                console.log("beforeUpdate()...");     
                let p = document.getElementById("p1").innerText;
                console.log(p);
           },
           updated(){
                console.log("update...");
                let p = document.getElementById("p1").innerText;
                console.log(p);
           },
           beforeDestroy() {
               console.log("beforeDesotry...");
               console.log(this.msg);  
               let p = document.getElementById("p1").innerText;
                console.log(p);
           },
           destroyed() {
              console.log("desotryed...");
               console.log(this.msg); 
               let p = document.getElementById("p1").innerText;
                console.log(p);
           },
        });
    </script>
</body>

6.Vue发送异步请求 [重点]

  • 在Vue.js中发送网络请求本质还是ajax,我们可以使用插件方便操作

    • XMLHttpRequest .send() - jquery
  • vue2.x 以前 使用 resource.js插件

    步骤1: 添加resource.js插件库
    步骤2: 使用vue-resource语法要求,发送get请求
    this.$http.get(url,{params:{id:1,name: 'zhangsan'}})
    
    url-请求的服务器地址
    请求参数方式1:{params:{id}}
    请求参数方式2: url?id=xxx&name=yyy
    

    参考代码:

    <script>
        //创建VM对象 
        var vm = new Vue({
            el: "#app", 
            data:{   
                list:[]
            },
            methods:{ 
                getData(){
                    //resource- get
                    //    this.$http.get("http://localhost/springboot-thymeleaf/userList",
                    //    {params:{userName:"z",age:20}}).then(res=>{
                    //        console.log(res.body);
                    //        this.list = res.body;
                    //    });
    
                    //    this.$http.get("http://localhost/springboot-thymeleaf/userList?userName=z&age=20").then(res=>{
                    //        console.log(res.body);
                    //        this.list = res.body;
                    //    });
    
                    this.$http.post("http://localhost/springboot-thymeleaf/userList",
                                    {userName:"z",age:20},{emulateJSON:true}).then(res=>{ 
                        //注:emulateJSON作用,将请求json参数转为 application/x-www-form-urlencoded格式
                        console.log(res.body);
                        this.list = res.body;
                    })
                } 
            },
            created(){
                //当页面加载时,发送异步请求获取数据
                this.getData(); //加载数据
            }
        });
    </script>      
    
  • vue2.x 以后 推荐使用 axios.js

http://www.axios-js.com/zh-cn/docs/

  • 并发执行多个异步请求:
执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));
  • 还可以使用axiosAPI来发送ajax请求:
axios(config)
// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

示例:

// axios.get("http://localhost/springboot-thymeleaf/userList",
//     {params:
//          {
//             userName:"z",
//             age:20
//         }
//     }).then(res=>{
//        // console.log(res);
//        this.list = res.data;
//     });

// axios.post("http://localhost/springboot-thymeleaf/userList",{ userName:"z", age:20})
//    .then(res=>{
//     // console.log(res);
//     this.list = res.data;
// });    

axios({
    url:"http://localhost/springboot-thymeleaf/userList",
    method:"post",
    data:{userName:"z", age:20}
}).then(res=>{
    this.list = res.data;
});  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值