功能:当用户输入电话号码后,先查找这个电话号码所在的省和市,然后再根据省和市,找到可能充值的面值,进行展示
//服务端代码const express = require('express');const app = express();// express.static 提供静态文件,就是html, css, js 文件app.use(express.static('./'));// 电话号码返回省和市,为了模拟延迟,使用了setTimeoutapp.post('/phoneLocation', (req, res) => { setTimeout(() => { res.json({ success: true, obj: { province: '广东', city: '深圳' } }) }, 1000);})// 返回面值列表app.post('/faceList', (req, res) => { setTimeout(() => { res.json( { success: true, obj: ['20元', '30元', '5元'] } ) }, 1000);})app.listen(3010, () => { console.log('server start');})
<!--客户端代码--><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Async/await</title><!-- CDN 引入vue 和 axios --><script src="https://cdn.jsdelivr.net/npm/vue"></script><script src="https://unpkg.com/axios/dist/axios.min.js"></script></head><body><div id="app"><input type="number" v-model.number="val"><!-- 输入框区域 --><div style="height:50px"><input type="text" placeholder="请输入电话号码" v-model="phoneNum"><button @click="getFaceResult">确定</button></div><!-- 充值面值 显示区域 --><div>充值面值:<span v-for="item in faceList" :key='item'>{{item}}</span></div></div><!-- js 代码区域 --><script>new Vue({el: '#app',data: {phoneNum: '12345',faceList: ["20元", "30元", "50元"],val: ""},methods: {//获取到城市信息getLocation(phoneNum) {return axios.post('phoneLocation', {phoneNum})},// 获取面值getFaceList(province, city) {return axios.post('/faceList', {province,city})},// async方式async getFaceResult() {let location = await this.getLocation(this.phoneNum);if (location.data.success) {let province = location.data.obj.province;let city = location.data.obj.city;let result = await this.getFaceList(province, city);if (result.data.success) {this.faceList = result.data.obj;}}},// promise方式getFaceResult() {this.getLocation(this.phoneNum).then(res => {if (res.data.success) {let province = res.data.obj.province;let city = res.data.obj.city;this.getFaceList(province, city).then(res => {if (res.data.success) {this.faceList = res.data.obj}})}}).catch(err => {console.log(err)})}}})</script></body></html>