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

我正在使用 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 函数。提前致谢


www说
浏览 174回答 2
2回答

慕桂英546537

您可以像这样添加一个已安装的 () 实例。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 方法

米琪卡哇伊

为什么不使用 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 方法中声明异步函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript