【vue】与springboot后台项目数据交互

最近在使用vue和springboot前后端分离的方式开发项目
遇到了很多问题

身份认证

这里本可以用vuex,但是由于偏轻量级,用vuex会比较复杂,于是我在main.js里定义了一个全局变量,以达到控制身份的效果

var state={
    islogin:false,
    manager:false,
    identify:{
        name:'null',
        email:'null',
    },
    login(name,manager,email){
        this.islogin=true;
        this.identify.name=name;
        this.manager=manager;
        this.identify.email=email;
    },
    logout(){
        this.islogin=false;
        this.identify.name='null';
        this.manager=false;
        this.identify.email='null';
    }
}

Vue.prototype.state=state

在用户请求路径的时候,在create函数里判断身份信息,然后选择是否成功访问


表单绑定

为了将表单数据提交,可以把表单数据通过v-model绑定到一个数组里

<template>
  <div>
    <div class="login">
    <myHeader/>  
    <form class="theform" id="demo_11" autocomplete="off">
        <div class="form-group">
            <input class="form-control" v-model="theform.email" placeholder="email" type="email">
        </div>
        <div class="form-group">
            <input @change="changePw" v-model="theform.password" class="form-control" placeholder="密码" type="password" maxlength="8">

        </div>
        <p style="color:red" v-show="pflag">{{message}}</p>
        <button class="btn btn-success" @click.prevent="login" type="submit">{{loginmessage}}</button>
        &nbsp;&nbsp;
        <button type="reset" class="btn btn-danger">{{reset}}</button>
        &nbsp;&nbsp;
        <button type="button" @click="toRegister" class="btn btn-primary">{{register}}</button>
    </form>
    </div>
    <myFooter/>
  </div>
</template>

<script>
import myHeader from '../components/header.vue'
import myFooter from '../components/footer.vue'
import qs from 'qs'
export default {
  components: { myHeader, myFooter },
  data() {
    return {
       loginmessage:"登陆",
       reset:"重置",
       register:"注册",
       message:"密码为3-8位字母或数字",
       theform:{
          email:"",
          password:"",
       },
       pflag:false
    }
  },
  created() {

  },
  methods: {
      changePw:function(){
        var reg=/[a-zA-Z0-9]{3,8}$/;
        if(!reg.test(this.theform.password)){
          this.pflag=true;
          return;
        }
        this.pflag=false;
      },
      toRegister:function(){
        this.$router.push({path:'/register'});
      },
      login:function(){
          let me=this;
          let params=qs.stringify(this.theform);
          this.$axios.post('login',params,function(r){
            if(!r.islogin){
              alert("邮箱或密码错误");
              me.$router.push({path:'/'});
            }else{
              me.state.login(r.name,r.manager,r.email);
              if(r.manager){
                me.$router.push({path:''});
              }else{
                me.$router.push({path:''});
              }
            }
          });
      } 
  }
}
</script>

<style type="text/css" src="@/style/login.css"></style>

axios请求

在使用axios发送请求时,我使用的在另一篇博客里用到的axios接口函数,在处理字符串时会报错,怎么也无法解决,最终我只能把下面这行注释

/*      o[key] = o[key].trim()*/

通过看接口代码,发现我们在后台需要返回数据里有success属性,否则会弹框打印信息。

package com.me.controller;  

import com.me.beans.ReturnMessage;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.ResponseBody;  
import org.springframework.web.bind.annotation.RestController;  

import java.util.HashMap;  

@RestController  
public class LoginController {  

    @RequestMapping("/login")  
    @ResponseBody  
  public HashMap login(@RequestParam("email")String email, @RequestParam("password")String password){  
        System.out.println("I AM COMING!============");  
  System.out.println(email);  
  System.out.println(password);  

  HashMap<String,Object> hashMap=new HashMap<>();  
  hashMap.put("success",true);  
  hashMap.put("islogin",false);  
  hashMap.put("ismanager",true);  
  hashMap.put("email","");  
  hashMap.put("name","");  

 return hashMap;  
  /*writer.write("success!!");*/  
  }  

    @RequestMapping("/sendcode")  
    @ResponseBody  
  public ReturnMessage sendcode(@RequestParam("email")String email){  
        System.out.println(email);  
 return new ReturnMessage(true);  
  }  
}

后台需要返回json格式的数据,使用@ResponseBody会帮我们自动把返回的数据转换为json格式。使用时还遇到了这个错误

https://www.cnblogs.com/gyjx2016/p/5896138.html
只需要把@Controller改为@RestController注解即可(由于前后端分离,@controller注解并没有什么用)

前台在提取的时候只需要把success函数里的r提出来用r.属性名就可以了

另外,get请求会把参数放在url后面
所以请求时参数应写为{xxx:”xxx”}的格式
而post请求类型时,不能直接按上面的格式,或者用JSON.stringify()的格式,实际使用时,需要导入axios里的qs工具

import qs from 'qs'

然后对参数进行qs.stringify的操作
比如上面的表单里的数据,就用了

qs.stringify(this.theform)

实际使用时,要注意this的含义,可以在刚开始用一个变量来存储this,防止后面使用的时候丢失。


获取验证码

实现验证码60秒内禁止重新发送

  var num=60;
  var me=this;
me.$axios.get('sendcode',{email:me.rform.email});
  this.sflag=true;
  var timer=setInterval(function(){
      num--;
      me.send=num+'秒后刷新';
    if(num == 0){
       me.sflag=false;
       me.send='发送验证码';
       clearInterval(timer);
       timer=null;
    }
  },1000);

控制按钮能否点击上用了属性

:disabled="sflag"

通过变量sflag控制


大概功能都差不多