首页 > 解决方案 > 如何在最后使用 VueJs 设置值变量

问题描述

嗨,我有一个 axios 函数,我需要验证一个值,它会返回给我 1 或 0,它可以工作,但问题是我需要在 axios 函数的最后部分设置这个值,我的代码是这个:

axios.post('/api/employee/verify?api_token='+App.apiToken, formData, config)
      .then(function (response) {
         currentObj.success = response.data.success;
         this.$set(this.form, 'search_data', response.data.success);
})
.catch(function (error) {
    console.log(error);
})
.finally(() => {
   if(currentObj.success == 1) {
      this.$awn.success("El colaborador ha trabajado con nosotros", {labels: {success: "Encontrado"}});
      this.$router.push('/employee/confirm');
  } else {
      this.$awn.alert("El colaborador no ha trabajado con nosotros", {labels: {success: "No Encontrado"}});
      this.$router.push('/employee/create');
  }
                        
  this.loading = false;
 });

你怎么能看到 axios 函数有一个 .finally 部分并且它有 currentObj.success 事情是它说它是未定义的,但它不是,我想知道如何设置我在 .finally 中收到的值axios函数?谢谢

标签: vue.js

解决方案


finally()通常用于在 Axios 请求成功与否时执行一些操作。你应该以另一种方式面对这个问题。

如果您正在开发自己的 API,最好的选择是在没有找到/验证员工的情况下返回 a404或任何相关代码。error因此你的 vue js 可能像

axios.post('/api/employee/verify?api_token='+App.apiToken, formData, config)
    .then((response) => {
        this.$set(this.form, 'search_data', response.data.success)
        this.$awn.success("El colaborador ha trabajado con nosotros", {labels: {success: "Encontrado"}})
        this.$router.push('/employee/confirm')
    })
    .catch((error) => {
        console.log(error)
        this.$awn.alert("El colaborador no ha trabajado con nosotros", {labels: {success: "No Encontrado"}})
        this.$router.push('/employee/create')
    })
    .finally(() => {                                
        this.loading = false
    })

如果更改 API 响应不是您的选择,那么只需按照您的承诺移动您的finally代码then()

axios.post('/api/employee/verify?api_token='+App.apiToken, formData, config)
    .then((response) => {
        currentObj.success = response.data.success
        this.$set(this.form, 'search_data', response.data.success)

        if(currentObj.success == 1) {
            this.$awn.success("El colaborador ha trabajado con nosotros", {labels: {success: "Encontrado"}})
            this.$router.push('/employee/confirm')
        } else {
            this.$awn.alert("El colaborador no ha trabajado con nosotros", {labels: {success: "No Encontrado"}})
            this.$router.push('/employee/create')
        }
    })
    .catch((error) => {
        console.log(error)
    })
    .finally(() => {                                
        this.loading = false
    })

推荐阅读