Vue综合案例:自定义指令,生命周期,v-resource请求

本文展示了一个使用Vue.js实现的品牌管理页面,包括添加、搜索和删除品牌的功能。页面中应用了Vue的v-model、v-for、事件绑定、自定义指令和过滤器。同时,使用了vue-resource进行API交互,处理数据展示和搜索过滤。此外,还涉及到了Vue的全局和私有过滤器、自定义指令的定义和使用。
摘要由CSDN通过智能技术生成
<!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>品牌案例</title>
    <style>
        [v-cloak]{
	      display:none;
         }
    </style>
</head>
<body>
    <div id='app' v-cloak>
        <div class='panel  panel-primary'>
             <div class='panel-heading'>
                <h3 class="panel-title">添加品牌</h3>
             </div>
             <div class="panel-body form-inline">
                <label>
                    id:
                    <input type="text" class="form-control" v-model='id'>
                </label>
                <label>
                    Name:
                    <input type="text" class="form-control" v-model='name' @keyup.f2='add'>
                </label>
                <!--在vue中,使用事件 绑定机制,为元素指定处理函数的时候,加了()就能为函数传递参数了-->
                <input  type="button" value="添加"  class="btn btn-primary" @click='add'>
                <label>
                    keywords:
                    <input type="text" class="form-control" v-model='keywords' id='search' v-focus v-color="'blue'">
                </label>
            </div>
        </div>
        <table class="table table-bordered table-hover table-striped">
            <thead>
                <tr>
                    <th>id</th>
                    <th>Name</th>
                    <th>Ctime</th>
                    <th>Opration</th>
                </tr>
            </thead>
            <tbody>
                <!--之前 ,v-for 中的数据,都是直接从 data上的List中直接渲染过来的-->
                <!-- 现在 ,我们自定义一个search()方法,同时,把搜索的关键字,通过传
                参的形式,传递给了search 方法-->
                <!--
                    在search方法内部,通过 执行fro循环,把所符合封装到一个数组中
                -->
                <tr v-for='item in search(keywords)' :key='item.id'>
                    <td >{{item.id}}</td>
                    <td >{{item.name}}</td>
                    <td >{{item.ctime | dateFormat()}}</td>
                    <td >
                        <a href='' @click.prevent='del(item.id)'>删除</a>
                    </td>
                </tr>
            </tbody>
        </table>
        <div>
            <!--管道过滤符-->
            <!-- <p>{{msg | msgFormat('疯狂+1','233') | test() }}</p> -->
        </div>

    </div>
    <!--所谓的全局的过滤器,是所有的vm共有-->
    <div id='app2' v-cloak>
        <p v-color="'pink'" v-fontweight="'900'">{{dt | dateFormat('yyyy-MM-dd-hh-mm-ss')}}</p>
        <h3></h3>
    </div> 
    <script src="https://cdn.bootcss.com/vue/2.5.2/vue.min.js"></script>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
    <script src="https://cdn.bootcdn.net/ajax/libs/vue-resource/1.5.2/vue-resource.js"></script>
    <!-- <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> -->

  <!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
    <script>
        Vue.config.keyCodes.f2=113;
          //定义一个全局的过滤器,名字叫做  msgFormat
        //第一个参数可以是字符串,也可以是一个正则表达式
       Vue.filter('msgFormat',function(msg,arg,arg2){
          return msg.replace(/单纯/g, arg+'\t'+arg2);
       });
       Vue.filter('test',function(msg){
              return  msg+'-------';
       });
       Vue.filter('dateFormat',function(dateStr){
        //根据给定的时间字符串,得到特定的时间    
        console.log('2222'); 
        var dt=new Date(dateStr);
        // yyyy-MM-dd
        var  year=dt.getFullYear();
        var month=dt.getMonth()+1;
        var  day=dt.getDate();
        return    `${year}-${month}-${day}`;

       });
       //vue 自定义指令
       //注意 : Vue中所有的指令 ,在调用的时候 ,都以 v- 开头
       //在定义的时候,不需要加v-前缀,在调用的时候必须在指令名称前加v-前缀
       //参数2:是一个对象,这个对象身上,有一些指令相关的函数,这些函数可以在特定的阶段
       //执行相关的操作
       Vue.directive(
        'focus',
         {
             bind:function(el){//每当指令绑定在元素上的时候,会立即执行这个Bind函数
               //注意,在每个函数中,第一个参数永远是el,表示,被绑定指令的元素,这个el就是原生的Js对象
              //在元素,刚绑定了指令的时候,还没有 插入到DOM中去,这时候focus方法没有作用
              //因为 ,一个元素,只有插入到DOM之后,才能获取到焦点
               el.focus();

            },
            //和js的行为有关的操作
             inserted:function(el){//这个表示 元素插入到dom中的时候,会执行inserted
                // el.focus();
             },
             updated:function(){//在Vnode更新的时候,会更新Update 可能会触发多次
                 
             }
         }

       );
       //自定义一个设置颜色的指令
       Vue.directive('color',{
           //样式,只是通过指令绑定给了元素,不管这个元素有没有被插入到页面中去,这个元素肯定有有一个内联样式
           //将来元素肯定会显示到页面中去,这时候,浏览器的渲染引擎必然会解析这个样式 
           bind:function(el,binding){
              // console.log(binding);
               el.style.color=binding.value;
           }
       })
        var   app=new   Vue( 
           {
             el:'#app',
             data:{
                 msg:'曾经,我是一个单纯的少年,单纯的我,傻傻的问,谁是世界上最单纯的人',
                 id:'',
                 name:'',
                 keywords:'',
                 list:[
                    {id:1,name:'奔驰',ctime:new Date()},
                    {id:2,name:'特斯拉',ctime:new Date()}
                ]
             },
             methods:{
                   add(){
                   
                    this.list.push({id:this.id,name:this.name,ctime:new Date()});
                 //   this.getAllList();
               //  this.jq();
               this.allList();
                },
                allList(){
                    this.$http.get("http://localhost:37250/VueTest/v1/GetAllCarList")
                  .then(function(result){
                      //通过result.body来拿到服务器的结果
                    console.log(result.body);
                    this.list=result.body.Result;
                    console.log(this.list);

                  }).catch((e)=>{console.log(e);});
                },
                jq(){
                    console.log('jq');
                    $.ajax({
                     url: "http://localhost:37250/VueTest/v1/GetAllCarList",
                    type: "GET",
                    success: function (response) {
                        
                       var result = JSON.stringify(response); //json对象转成字符串
                       console.log(response.IsOk);
                       if(response.IsOK){
                        //    for (let index = 0; index < response.Result.length; index++) {
                        //            debugger
                        //            var item=response.Result[index];
                        //            var arr=[];
                        //            arr.push(item);
                        //            console.log(arr);
                        //            this.list.push(item);
                        //    
                        this.list=response.Result;
                     } 

                     },
                     error:function(error){
                         console.log(error);
                     }
                 });
                },
                 getAllList(){
                     console.log('getalllist');
						this.$http.jsonp('http://localhost:63822/VueTest/v1/GetAllCarList',{
							params:{
							},
							jsonp:'cb'
						}).then(resp => {
                            debugger
                             console.log(resp);
                        }).catch((e)=>{console.log(e);}); 
                // axios.get('http://localhost:63822/VueTest/v1/GetAllCarList')
                //          .then(function (response) {
                //              console.log(response);
                //          })
                //          .catch(function (error) {
                //              console.log(error);
                //          });

                    },
                   del(id){
                        //分析
                        //1.如何根据id ,找到要删除的这一项的索引
                        //2. 如果找到索引了,直接调用 数缓征 里的splice方法
                      // console.log(id);
                    //    this.list.some((item,i)=>
                    //    {
                    //        if(item.id==id){
                    //            this.list.splice(i,1);
                           
                    //            //在数组的some方法中,如果 return true,就会立即终止这个数组的后续循环动作
                    //            return  true;
                    //        }
                    //    }
                       var index  =this.list.findIndex(item=>{
                                   if(item.id==id){
                                       return true;
                                   }
                               });
                       console.log(index);
                       this.list.splice(index,1);
                   },

                   search(keywords){
                       console.log(keywords);
                       if(keywords.trim()==''){
                        return this.list;
                       }
                   var newList=[];
                    //    this.list.forEach(
                    //        item=>{
                    //            if(item.name.indexOf(keywords)!=-1){
                    //                 newList.push(item);
                    //              }
                    //          }
                    //    );
                    //    return  newList;
                    //注意: forEach  some   filter   findIndex 这些都属性于数组的新方法
                    //都会对数组中的每一项 进行遍历,执行相关的操作
                    newList=  this.list.filter(item=>{
                        if(item.name.includes(keywords))
                        {
                              return  item;
                         }
                    });
                      return newList;
                   }
                }
            }
        );
        var vm2=new Vue(
            {
                el :'#app2',
                data:{
                    dt:new Date('2021-07-07')
                },
                filters:{
                    //定义私有的过滤器,过滤器有两个条件 {过滤器名称 和处理函数}
                    dateFormat :function(dateStr,pattern='yyyy-mm-dd'){
                         var dt=new Date(dateStr);
                         var y=dt.getFullYear();
                         var m=(dt.getMonth()+1).toString(2,'0');
                         var d=(dt.getDate()).toString(2,'0');
                         if(pattern.toLowerCase()==='yyyy-mm-dd'){
                             return  `${y}-${m}-${d}`;
                         }else{
                             var hh  =dt.getHours();
                             var  mm=dt.getMinutes();
                             var  ss=dt.getSeconds();

                             return   `${y}-${m}-${d}-${hh}-${mm}-${ss}`;
                         }
                    }
                },
                directives:{//自这义私有指令
                    'fontweight':{
                        bind:function(el,binding){
                            console.log(binding);
                            el.style.fontWeight=binding.value;
                        }
                    }
                }
            }
        );
       //  document.getElementById('search').focus();
      </script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值