vue在回调函数中赋值到data,然后再从data中获取之前的赋值,能否在created之后的地方获取到?


<script>
import { getOrderList, getUserList } from '@/api/pageInfo.js'
export default {
  data() {
    return {
      orderList: [],
      userList: []
    }
  },
  created() {
    this.reload()
    this.getUserLists()
  },
  methods: {
    reload() {
      const datas = {
        page: this.currentPage,
        rows: this.currentRows
      }
      getOrderList(datas) .then(res => {
           this.orderList = res.data.list
      })
      console.log(this.userList)
      console.log(this.orderList)
    },
    getUserLists() {
      const datas = {
        page: this.currentPage,
        rows: this.currentRows
      }
      getUserList(datas).then(res => {
        this.userList = res.data.list
      })
      console.log(this.userList)
      console.log(this.orderList)
    }
  }
}
</script>
请问有大佬知道,这四个console.log()是不是都能拿到值

ajax 回调函数默认的请求方式是异步的,你需要去了解下ajax异步的概念

  getUserList(datas).then(res => {
    this.userList = res.data.list
  })
  console.log(this.userList)
  console.log(this.orderList)

是先执行console.log(this.userList) console.log(this.orderList)
之后异步加载内容,再执行回调函数中的 this.userList = res.data.list

所以 console.log(this.userList) 输出的不是最新获取的内容, 而是上一次获取的内容

你要把console.log(this.userList) console.log(this.orderList)放到回调函数中,这样输出的才能是最新获取的内容

getUserList(datas).then(res => {
    this.userList = res.data.list
    console.log(this.userList)
    console.log(this.orderList)
})

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632