为了账号安全,请及时绑定邮箱和手机立即绑定

如何创建先运行的方法,然后再转到 vuejs 中的其他方法?

如何创建先运行的方法,然后再转到 vuejs 中的其他方法?

www说 2021-12-02 10:22:47
我正在使用 vuejs 和 axios 为 ajax 创建 CRUD 应用程序。我也在执行 CRUD 之前进行登录,但我想在执行 CRUD 之前验证用户在这种情况下我使用 vuejs 仅用于将数据从 ajax 渲染到 html我创建了一个用于将数据插入数据库的 insert 方法,以及从 ajax 返回 isLogin 结果的 check_login 方法。在插入方法的第一行中,我包含它以验证用户是否登录。但问题是我在我的应用程序中创建了 3 个以上的 CRUD,所以我认为这种方式并不简单,因为我总是必须创建从 check_login 方法获取返回值的变量。我的情况有什么解决方案吗? methods:{  check_login(){    axios.get(this.url+'login/check').then(function(response){    vue.login_result = response.data.status;        })    return this.login_result;  },   insert(){  let login_result = this.check_login();  if (!login_result) {  alert('you are not login');  }else{  //ajax insert here  }  },  }我想在做插入方法之前,check_login 方法会自动运行,也许它就像 php 中的 __construct 函数。提前致谢
查看完整描述

2 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

您可以像这样添加一个已安装的 () 实例。


mounted (){

   this.check_login()

},


methods:{

    check_login(){

        axios.get(this.url+'login/check').then(function(response){

            vue.login_result = response.data.status;    

        })

            return this.login_result;

    }, 


    insert(){

        let login_result = this.check_login();

        if (!login_result) {

            alert('you are not login');

        }else{

            //ajax insert here

        }

    },

}

页面加载时首先运行 check_login 方法


查看完整回答
反对 回复 2021-12-02
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

为什么不使用 ES6 异步等待?类似的东西


 methods:{

  async check_login(){

   return  axios.get(this.url+'login/check').then((response)=>

    response.data.status;    

    )

  }, 


  async insert(){

    let login_result = await this.check_login();

    if (!login_result) {

      alert('you are not login');

    }else{

      //ajax insert here

     }


  },


}

毕竟你可以在 vue 方法中声明异步函数。


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信