1. 程式人生 > >10.VUE學習之使用lodash庫減少watch對後臺請求的壓力

10.VUE學習之使用lodash庫減少watch對後臺請求的壓力

shee ext fun 改變 mod 減少 func 異步 監聽

問題描述

使用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‘]);
?>

10.VUE學習之使用lodash庫減少watch對後臺請求的壓力