zoukankan      html  css  js  c++  java
  • 10.VUE学习之使用lodash库减少watch对后台请求的压力

    问题描述

    使用watch监听库里word的值的变化,获取新值后,用oxios发送的ajax异步请求,
    此时会多次发送请求,浪费服务器资料.

    解决办法

    使用lodash库里的_.debounce函数延缓异步请求的时间,减少对后台请求的压力,设定库里值动态变化后在规定的时间后再异步请求

    步骤:

    1.安装lodash.

    npm install lodash

    使用说明:
    文档地址:
    https://www.css88.com/doc/lodash/#_debouncefunc-wait0-options

    2.页面里引入js

    <script type="text/javascript" src="../vue/node_modules/lodash/lodash.js"></script>
    

    3.使用_.debounce函数

    _.debounce(func, [wait=0], [options={}])
    

    4.完整代码:

    10.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>vue</title>
        <link rel="stylesheet" href="">
        <!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
        <script type="text/javascript" src="../js/vue.js"></script>
        <!---发送异步请求-->
        <script type="text/javascript" src="../vue/node_modules/axios/dist/axios.js"></script>
        <!---延缓异步请求的时间-->
        <script type="text/javascript" src="../vue/node_modules/lodash/lodash.js"></script>
    </head>
    <body>
    <div id="vue">
        <!--当input里的值改变时,会改变data里的word-->
        <input type="text" v-model="word">
        <h1>
            <!--拿到data里的result里的值-->
            结果:{{result}}
        </h1>
    </div>
    </body>
    <script type="text/javascript">
        var app=new Vue({
            el:'#vue',
            watch:{ //监听data里的word的变化
                //			拿到input里的新值和旧值
                word:_.debounce(
                        function(new_v,old_v){
                            //		        console.log(new_v+'=>'+old_v);
                            var url = '9.php?word='+new_v;
                            //				ajax get异步请求
                            axios.get(url).then(function(response){
                                console.log(response);
                                app.result = response.data //赋值给data里的result
                            });
                        },1000 //1秒后执行
                )
            },
            data:{
                word:'',
                result:''
            }
        });
    </script>
    </html>
    

    10.php

    <?php
    /**
     * Created by PhpStorm.
     * User: Administrator
     * Date: 2019/1/5
     * Time: 10:42
     */
    
    
    print_r('要搜索的内容是:'.$_GET['word']);
    ?>
    
  • 相关阅读:
    ul制作导航菜单
    HTML5+CSS (简易nav设计)
    鼠标事件-拖拽(滑块控制物体透明度变化)
    鼠标事件-拖拽5(带虚线框的拖拽)
    鼠标事件-拖拽4(捕获)
    鼠标事件-拖拽3(磁性吸附)
    鼠标事件-拖拽2(不能拖出指定对象的div)
    生成整数排列的方法
    python工具程序一、复制目录中指定扩展名的文件
    Anaconda packages list
  • 原文地址:https://www.cnblogs.com/haima/p/10227584.html
Copyright © 2011-2022 走看看