1. 程式人生 > >09.1.VUE學習之watch監聽屬性變化實現類百度搜索欄功能ajax非同步請求資料,返回陣列

09.1.VUE學習之watch監聽屬性變化實現類百度搜索欄功能ajax非同步請求資料,返回陣列

09.1html裡

<!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裡的值-->
    </h1>

    <table border="1">
        <tr>
            <th>序號</th>
            <th>編號</th>
            <th>標題</th>
            <th>價格</th>
            <th>數量</th>
            <th>合計</th>
        </tr>
        <tbody>

        <!--拿到data裡的result裡的值-->
        <tr v-for="(v,k) in result">
            <td>{{k}}</td>
            <td>{{v.id}}</td>
            <td>{{v.title}}</td>
            <td>{{v.price}}</td> <!--每次都取name值,不變-->
            <td>{{v.num}}</td> <!--每次都取name值,不變-->
            <td>{{v.num*v.price}}</td> <!--每次都取name值,不變-->
        </tr>
        總價格:{{total}}
        </tbody>
    </table>
</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.1.php?word='+new_v;
                        //              ajax get非同步請求
                        axios.get(url).then(function(response){
                            console.log(response);
                            console.log(response.data.total);
                            app.total = response.data.total //賦值給data裡的result
                            app.result = response.data.content //賦值給data裡的result
                        });
                    },1000 //1秒後執行
            )
        },
        data:{
            word:'',
            result:'',
            total:0,
        }
    });
</script>
</html>

09.1.php裡

<?php

//print_r('要搜尋的內容是:'.$_GET['word']);

$data = [
           'total'=>0,
            'content'=>array(
                ['id' => 1, 'title' => 'iphone7Plus', 'price' => 300, 'num' => 3,],
                ['id' => 2, 'title' => 'hdcms系統', 'price' => 1999, 'num' => 9],
            ),

];
$total=0;
foreach($data['content'] as $k=>$v){
    $total+=$v['price']*$v['num']; //計算總價
}
$data['total']=$total;
echo json_encode($data);
?>

效果: