如何使用promise改写我的代码?

新手,大佬轻点喷,vue2项目,搜索框用的原生,请求数据用的axios
我在项目中写了一个搜索框,目前数据的静态的,我想动态获取数据,但数据是异步请求获取的,如果我像下面直接这样赋值会获取不到值,我想使用promise改写,请问以下应当如何改写

代码:

<template>
  <div class="serUser">
<!--    将用户数据动态渲染出来-->
    <h1>欢迎进入用户管理界面</h1>
<!--  搜索框  -->
    <div id="container">
      <div class="sea-container">
        <form action="">
          <input type="text" name="search" class="blue-input" >
          <input type="submit" value="搜索" class="blue-button">
        </form>
        <p id="selectedId"></p>
      </div>
    </div>
<!--    -->
    <ul v-for="(data,index) of userData" :key="index">
      <li>第{{index+1}}位用户的ID为:{{data.username}}</li>
      <li>第{{index+1}}位用户的密码为:{{data.password}}</li>
      <li>
        <button @click="changeUser()">编辑</button>
        <button @click="deleteUser(index)">删除</button>
      </li>
    </ul>
  </div>
</template>
<script type="text/ecmascript-6">
import axios from "axios";

export default {
  data(){
    return{
      userData:[]
    }
  },
  methods:{
    changeUser(){
      alert("修改我没写哦,但是可以删除")
    },
    deleteUser(index){
      const flag = this.areYouSureDelete()
      if(flag){
        this.userData.splice(index, 1)
        const deleteUser = this.userData
        axios.get("http://192.168.198.1/admin/deleteUser",{
          params:{
            deleteUser:deleteUser
          }
        }).then(res=>{},error=>{console.log("请求失败", error)})
      }
    },
    areYouSureDelete(){
      return confirm("确定删除吗!");
    },
//传入this.userData返回此数据用的所有username
    initUserData(data){
      if(!(data instanceof Array)){
        return
      }
      let newData = []
      for (let i = 0; i < data.length; i++) {
        newData.push(data[i].username)
      }
      return newData
    }
  },
  mounted() {
    axios.get("http://192.168.198.1/admin/userShow")
      .then(res=>{
        this.userData = res.data.data
        // console.log("请求成功", this.userData[0].password)
      },error=>{
        console.log("请求失败", error)
      })

    let arr = ["user","userNo1","userNo25","userNo99","userNo123","userNo1","abcd","asgh","asdasd","fsaas","ssda","admin","userZhangSan"];
    // let arr = this.userData
    // console.log(arr)
    let search = document.getElementsByClassName("blue-input")[0];
    let selectedId = document.getElementById("selectedId")
    function showList(){
      let res = searchByIndexOf(search.value,arr);
      console.log(res)
      for(let i=0;i<res.length;i++){
        let li = document.createElement("li");
        li.innerHTML = res[i];
        document.getElementById("drop").appendChild(li);
      }
    }
    search.oninput = function getMoreContents() {
      // 添加删除ul
      let drop = document.getElementById("drop");
      selectedId.removeChild(drop);
      let originalUl = document.createElement("ul");
      originalUl.id = "drop";
      selectedId.appendChild(originalUl);
      showList();
    }
    search.onfocus = function(){
      let originalUl = document.createElement("ul");
      originalUl.id = "drop";
      selectedId.appendChild(originalUl);
      showList();
    }
    search.onblur = function(){
      let drop = document.getElementById("drop");
      selectedId.removeChild(drop);
    }

//模糊查询
    function searchByIndexOf(keyWord, list){
      if(!(list instanceof Array)){
        return ;
      }
      if(keyWord == ""){
        return [];
      }else{
        let len = list.length;
        let arr = [];
        for(let i=0;i<len;i++){
          //如果字符串中不包含目标字符会返回-1
          if(list[i].indexOf(keyWord)>=0){
            arr.push(list[i]);
          }
        }
        return arr;
      }

    }
  }
}
</script>
<style  scoped>
h1{
  font-size: 28px;
  text-align: center;
  padding-top: 40px;
}
ul{
  padding: 60px 0 0 30%;
}
ul li {
  padding-bottom: 12px;
}

#container {
  width: 800px;
  height: 150px;
  margin: 0 auto 150px;
  padding-top: 30px;
  box-sizing: border-box;
}

/*搜索栏*/
.sea-container {
  width: 450px;
  height: 30px;
  background-color: green;
  margin: 50px auto 150px;
  border: 1px solid #317EF3;
  /*padding-bottom: 150px;*/
}
.blue-input {
  float: left;
  width: 350px;
  height: 30px;
  padding: 0 10px;
  box-sizing: border-box;
}
.blue-button {
  width: 100px;
  height: 30px;
  background-color: #317EF3;
  color: white;
  font-size: 15px;
}
/* 搜索下拉框*/
ul#drop {
  list-style: none;
  margin: 0;
  padding: 0;
}
ul#drop li {
  margin: 0;
  padding: 10px;
}

ul#drop li:hover {
  background-color: darkgrey;
  width:200px;
}

p#selectedId {
  display: inline-block;
}
</style>

后台的json数据
{"admin":[{"username":"admin","password":"123456"}],
  "users": [
    {
      "username": "user",
      "password": "123456"
    },
    {
      "username": "userNo1",
      "password": "123456"
    },
    {
      "username": "userNo99",
      "password": "123456"
    },
    {
      "username": "userZhangSan",
      "password": "123456"
    },
    {
      "username": "userLisi",
      "password": "123456"
    },
    {
      "username": "AASD",
      "password": "SSDA"
    }
  ]}
阅读 1k
4 个回答

2023 年了,用 async/await 吧,在异步操作前加一个 await,再把自己的函数前加一个 async,剩下的就跟写同步函数差不多。

async mounted() {
  // 这里最好加一个错误处理,网络请求很容易出错
  const data = await axios.get('....');
  this.userData = data;

  // 后面也不要再手动操作 dom 了,直接写成模版吧
}

1、axios的get方法返回的就是一个包装过的Promise对象
2、如果你原先的想法是想要把在then()方法里等待请求被满足后返回的值赋给arr,那大可以在get方法前先初始化arr,在then()里把res.data.data直接给arr就行了:

mounted(){
    let arr = [];
    axios.get(xxx).
    then((res)=>{
        this.userData=res.data.data;
        arr = this.userData;
    }).
    catch(error=>console.log("请求失败",error));
}

使用 async/await

-  mounted() {
-    axios.get("http://192.168.198.1/admin/userShow")
-      .then(res=>{
-        this.userData = res.data.data
-        // console.log("请求成功", this.userData[0].password)
-      },error=>{
-        console.log("请求失败", error)
-      })
+  async mounted() {
+    arr = await axios.get("http://192.168.198.1/admin/userShow")
+      .then(res=>{
+        return res.data.data
+      })

-     let arr = ["user","userNo1","userNo25","userNo99","userNo123","userNo1","abcd","asgh","asdasd","fsaas","ssda","admin","userZhangSan"];

方法1、对于promise异步回调,搜索框的设置可以直接写在回调里面

axios.get("http://192.168.198.1/admin/userShow")
      .then(res=>{
        this.userData = res.data.data
        let arr = ["user","userNo1","userNo25","userNo99","userNo123","userNo1","abcd","asgh","asdasd","fsaas","ssda","admin","userZhangSan"];

        // ... 其他代码:搜索框的设置等

      },error=>{
        console.log("请求失败", error)
      })

方法2、使用async/await组合

async mounted() {
  try {
    // 通过await实现异步调用api接口
    const res = await axios.get("http://192.168.198.1/admin/userShow")
    this.userData = res.data.data;
    let arr = ["user","userNo1","userNo25","userNo99","userNo123","userNo1","abcd","asgh","asdasd","fsaas","ssda","admin","userZhangSan"];

    // ... 其他代码:搜索框的设置等

  } catch (error) {
    console.error("Failed to fetch or process data:", error);
  }
}

望采纳哈O(∩_∩)O

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏