功能:当用户输入电话号码后,先查找这个电话号码所在的省和市,然后再根据省和市,找到可能充值的面值,进行展示

                
  1. //服务端代码
  2. const express = require('express');
  3. const app = express();// express.static 提供静态文件,就是html, css, js 文件
  4. app.use(express.static('./'));
  5. // 电话号码返回省和市,为了模拟延迟,使用了setTimeout
  6. app.post('/phoneLocation', (req, res) => {
  7. setTimeout(() => {
  8. res.json({
  9. success: true,
  10. obj: {
  11. province: '广东',
  12. city: '深圳'
  13. }
  14. })
  15. }, 1000);
  16. })
  17. // 返回面值列表
  18. app.post('/faceList', (req, res) => {
  19. setTimeout(() => {
  20. res.json(
  21. {
  22. success: true,
  23. obj: ['20元', '30元', '5元']
  24. }
  25. )
  26. }, 1000);
  27. })
  28. app.listen(3010, () => {
  29. console.log('server start');
  30. })
  1. <!--客户端代码-->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>Async/await</title>
  7. <!-- CDN 引入vue 和 axios -->
  8. <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  9. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  10. </head>
  11. <body>
  12. <div id="app">
  13. <input type="number" v-model.number="val">
  14. <!-- 输入框区域 -->
  15. <div style="height:50px">
  16. <input type="text" placeholder="请输入电话号码" v-model="phoneNum">
  17. <button @click="getFaceResult">确定</button>
  18. </div>
  19. <!-- 充值面值 显示区域 -->
  20. <div>
  21. 充值面值:
  22. <span v-for="item in faceList" :key='item'>
  23. {{item}}
  24. </span>
  25. </div>
  26. </div>
  27. <!-- js 代码区域 -->
  28. <script>
  29. new Vue({
  30. el: '#app',
  31. data: {
  32. phoneNum: '12345',
  33. faceList: ["20元", "30元", "50元"],
  34. val: ""
  35. },
  36. methods: {
  37. //获取到城市信息
  38. getLocation(phoneNum) {
  39. return axios.post('phoneLocation', {
  40. phoneNum
  41. })
  42. },
  43. // 获取面值
  44. getFaceList(province, city) {
  45. return axios.post('/faceList', {
  46. province,
  47. city
  48. })
  49. },
  50. // async方式
  51. async getFaceResult() {
  52. let location = await this.getLocation(this.phoneNum);
  53. if (location.data.success) {
  54. let province = location.data.obj.province;
  55. let city = location.data.obj.city;
  56. let result = await this.getFaceList(province, city);
  57. if (result.data.success) {
  58. this.faceList = result.data.obj;
  59. }
  60. }
  61. },
  62. // promise方式
  63. getFaceResult() {
  64. this.getLocation(this.phoneNum)
  65. .then(res => {
  66. if (res.data.success) {
  67. let province = res.data.obj.province;
  68. let city = res.data.obj.city;
  69. this.getFaceList(province, city)
  70. .then(res => {
  71. if (res.data.success) {
  72. this.faceList = res.data.obj
  73. }
  74. })
  75. }
  76. })
  77. .catch(err => {
  78. console.log(err)
  79. })
  80. }
  81. }
  82. })
  83. </script>
  84. </body>
  85. </html>