Vue 使用lodash库减少watch对后台请求压力

  作者: thtomatic  分类: Vue   评论: [ 0 ] 条  浏览: [ 842 ] 次

watch的使用方法可以看我上一篇的博客<<vue 使用watch监听实现类似百度搜索功能>>

lodash需要新引入

我使用的是npm方式

使用lodash的_.debounce方法

具体代码:


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue.js 使用lodash库减少watch对后台请求压力 </title>
    <script src="vue.js"></script>
    <script src="node_modules/axios/dist/axios.js"></script>
    <script src="node_modules/lodash/lodash.js"></script>
</head>
<body>
<div id="ask"><!--vue不能控制body和html的标签-->
    <input type="text" v-model="word">
    <h1>{{result}}</h1>
</div>
<script>
    var app = new Vue({ //实例化vue
        el:'#ask',//vue控制id为ask的元素,
        //watch 可以监听多个变量
        watch:{
            //监听word变量
            word:_.debounce(function (newV,oldV) {
                console.log('旧值:'+oldV+'=======>新值:'+newV);
                //这里可以写异步请求我用的是axios
                axios.get('Api.php?word='+newV).then(function (res) {
                    console.log(res,'这是异步返回的值');
                    //这里写异步得到值之后的动作
                    app.result=res.data;
                });
            },3000)
        },
        data:{
            word:'',
            result:''

        }
    });
</script>
</body>
</html>


效果:



版权所有:《thtomatic》 => 《Vue 使用lodash库减少watch对后台请求压力
本文地址:https://ask.mykeji.net/Vue/231.html
除非注明,文章均为 《简单记录》 原创,欢迎转载!转载请注明本文地址,谢谢。


发表评论:

    42.81ms