vue+springboot小项目的经验之道

去年写一个小项目,与layui结缘,用起来不得说,对于我们这种后台开发人员写起界面来也方便了很多,要想要是自己设计能力好的话,css学的足够精通,还学UI库干什么呢。当然,使用ui库,真的可以提高我们的开发效率。上周接了一个别人的毕设项目,本来就很有兴趣学习一下vue,这不就 ,边学边学用了10+天。

layui的面纱

layui作为一个前端UI项目,我用的最多的还是它的弹窗…,其他树形组建也没用过。官方的文档 也写的蛮详细的,这里我就不提了,因为自己也很菜。就是想总结一下常用的一些技巧使用。

场景1、当我们想点击不同的单选框,然后刷新对应的下拉框的值。

以下${goods}是后台通过模板引擎分装的数据,循环输出所有商品类型,要的效果就是点击不同的商品类型刷新下拉框列表的数据。

	  <div class="layui-form-item">
            <label class="layui-form-label">商品类型</label>
            <div class="layui-input-block">
              <span th:each="good : ${goods}" th:onclick="'javascript:changeSelect('+${good.id}+')'"  >
                <input  name="select" type="radio" th:value="${good.id}"
                       th:title="${good.column_type}" >
              </span>


            </div>
          </div>
            <div class="layui-form-item">
                <label class="layui-form-label">上架栏目</label>
                <div class="layui-input-block">
                  <div  id="column"  >
                    <select name='type' >
                      <option value="">请选择上架栏目</option>
                    </select>

                  </div>
                </div>
            </div>

对应的js实现:

	 function changeSelect(index) {
              console.log(index)
               $("#column").html("");
                let str ="<select name='type' >";
              for (let j = 0; j < data[index].goods_typeList.length; j++) {
                let id = data[index].goods_typeList[j].id;
                let text = data[index].goods_typeList[j].small_column
                str += '<option value="'+id+'">'+text +'</option>';
              }
              str += '</select>'
              $("#column").html(str)
              console.log(str)
              layui.form.render('select');
            }

场景二、layui、elementUI、axios、echarts混搭使用

我本来以为elementUI跟layui搭配应该会不兼容,可能是我太菜了才会这么觉得吧。其实还不错。

引入elementUI、CDN相关CDN地址即可


 <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
 <!-- vue  -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- elementUI JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="/js/echarts.min.js"></script>

然后javascript写如下即可使用axios、charts

 Vue.prototype.$axios = axios;
 Vue.prototype.$echarts = echarts;

最后说一点 在vue中 axios的常用请求方法:
如果在axios想实现跨域请求,我们需要在脚手架工程文件config/index.js里面设置如下内容:
1.配置访问请求主机

proxyTable: {
      '/api': {
        target: 'http://localhost:80',//设置你调用的接口域名和端口号 别忘了加http、https
        changeOrigin: true,//是否跨域
        secure: true, // 允许https请求
        pathRewrite: {
          '^/api': ''//这里理解成用‘/api’代替target里面的地址
        }
      }
    }
  1. vue启动 的 main.js 配置内容
    为什么要配置如下内容呢?这样每次跨域请求前面就不用加/api了。
axios.defaults.baseURL = '/api' 
Vue.prototype.$axios = axios

场景三、请求携带参数 springboot如何接收?

1. url组装型

如下请求,springboot不用多做配置,直接让参数名与该参数id名字保持一致即可。

 this.$axios.get("/recharge?id=" +  this.rechargeOrderId, { 
	 headers: { 
		 'Content-type': 'application/json;charset=UTF-8' 
 	}}).then(res => {
           console.log(res.data);
           }
})

2. post参数型

this.$axios.post("/order/cancelOrder", {
				// currOrderIdAll为一个数组。
               param: this.currOrderIdAll
            }, {
                  headers: {
                             'Content-type': 'application/json;charset=UTF-8'
                 }
               }).then(response => {
                        console.log(response);
                  }).catch(function (error) {
                          console.log(error);
                      });

这个时候我们该怎么接收参数呢?如下:

public JSONObject cancelOrder(@RequestBody JSONObject jsonObject){
        JSONObject res = new JSONObject();
        ArrayList<Integer> array = (ArrayList)jsonObject.get("param");
   }

那如果如下请求的参数是个json数据,后台怎么获取数据呢?

this.$axios.post("/lgoin", {
				// currOrderIdAll为一个数组。
               param: {
					id:"123",
					password:"dd"
				}
            }, {
                  headers: {
                             'Content-type': 'application/json;charset=UTF-8'
                 }
               }).then(response => {
                        console.log(response);
                  }).catch(function (error) {
                          console.log(error);
                    });

如下:

public JSONObject login(@RequestBody JSONObject jsonObject){
       
        JSONObject  param = jsonObject.get("param");
        String vipId = param.getString("id");
        String password = param.getString("password");
   }

场景四、登陆后跳转到原界面(就是由哪个页面跳转过来的登陆成功应该返回原界面,用户体验效果自然是好)(VUE)

购物车付款时(假若用户没有登陆)这里提示需要登录,自然用户需要登陆的话要跳转到登陆界面,登陆成功我们应该返回到购物车这个页面。
我的解决方案是:跳转到 /login之前携带一个参数,这里是携带的即就是当前页面/shopping

 this.$confirm('登陆可享会员优惠95折,是否需要登录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push({ name: 'login', params: { redirect: "/shoppingCar" } });
          }).catch(() => {
            console.log(JSON.stringify(this.shoppingCar))
          });

登陆成功 应该取出传递过来的参数,并跳转过去即可


        this.$axios.post("/vip/login", {
            vipId: this.ruleForm.password
          }, {
            headers: {
              'Content-type': 'application/json;charset=UTF-8'
            }
          }).then(res => {
            console.log(res)
            if (res.data.state == 200) {
              //this.$router.go(-1);
              // window.history.back() 
              // 如果没有 要跳转的地址直接跳入
              let msg = res.data.message; 
              this.setUserInfo(JSON.parse(msg));
              if (JSON.stringify(this.$route.params) != '{}') {
                console.log("有目标地址传进来" + this.$route.params.redirect)
                // 这里写path比较灵活 写name(vue路由时设置的名字) 的话 如果目标地址携带了参数还得 再用 params或者query传过去
                // 而path直接接受传来的参数即为要跳转的页面。
                this.$router.push({ path: decodeURIComponent(this.$route.params.redirect) });
              } else {
                console.log("没有目标地址传进来")
                this.$router.push({ name: 'personCenter' });
              }
            } else {
              this.$message({
                message: res.data.message,
                type: "error"
              });
            }
          }).catch(function (error) {
            console.log(error);
          });

场景五、路由权限设置(VUE)

有些页面,没有登陆状态应该是没有权限访问的,我们需要给路由配置权限,具体做法如下:
在路由配置js下:加入meta属性

{
      path: '/personCenter',
      name: 'personCenter',
      meta: {
        auth: true
      },
      component: personCenter,
      children: [
        {
          path: 'userInfo',
          component: userInfo
        },
       ]
 }

vue 启动的main.js 加入如下内容

router.beforeEach((to, from, next) => {
 //检测是否需要权限校验
  if (to.matched.some(record => record.meta.auth)) {
    console.log(to.fullPath+"需要验证")
  	// 检测是否登陆,没登陆则跳转到login界面
    if (userGlobal.alreadyLogin()) {
      next()
    } else {
      console.log("进入验证")
      //防止无限循环
      if (to.name === 'login') {
        next();
        return
      }
      next({
        path: '/login',
        redirect: to.fullPath
      });
    }
  } else {
    console.log(to.fullPath+"不需要验证")
    next()//若点击的是不需要验证的页面,则进行正常的路由跳转
  }

})

场景六、父子组件通信方案(VUE)

1.父组建引用子组建

<!-- ref即为起别名-->
<goodsWindow ref="goodsWindow" />
 import goodsWindow from "@/components/goodsWindow";
//vue组件加入该组建
 components: {
      goodsWindow
    }

这时候,父组建调用子组件很简单 ,直接使用this.$refs.goodsWindow即可获取子组建方法及属性。而子组建引用父组建更简单,直接使用this.$parent即可调用父组件方法及属性。当然这只是一种方法。还有其他好几种方法eg:props、$emit这里就不做过多的介绍了。

场景七、获取起始日期与终止日期的每一天

有时候我们需要获取起始日期与终止日期做个报表,那么前台传来 两个日期,后台肯定 需要解析出 每一天。

static List<String> findDaysStr(String begintTime, String endTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date dBegin = null;
		Date dEnd = null;
		try {
			dBegin = sdf.parse(begintTime);
			dEnd = sdf.parse(endTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		List<String> daysStrList = new ArrayList<String>();
		daysStrList.add(sdf.format(dBegin));
		Calendar calBegin = Calendar.getInstance();
		calBegin.setTime(dBegin);
		Calendar calEnd = Calendar.getInstance();
		calEnd.setTime(dEnd);
		while (dEnd.after(calBegin.getTime())) {
			calBegin.add(Calendar.DAY_OF_MONTH, 1);
			String dayStr = sdf.format(calBegin.getTime());
			daysStrList.add(dayStr);
		}
		return daysStrList;
	}

解析出每一天,然后通过如下SQL语句即可统计每天的消费总营业额。其中#{dateTime}为传来的参数。

SELECT sum(fmoney) as count FROM good_order WHERE 
date_format(created_time,'%Y-%m-%d')=date_format(#{dateTime},'%Y-%m-%d');

另外总结下在vue中 如何引入 外部 js 充当全局变量。
首先在 src新建一个util包,新建userGlobal.js ,内容格式如下:


function alreadyLogin(){
    return getUserInfo() !== '{}' ? true:false
}
function getUserInfo(){
    return sessionStorage.getItem('user')==null?'{}':JSON.parse(sessionStorage.getItem('user'));
}

function setUserInfo(user){
    sessionStorage.setItem('user',JSON.stringify(user))
}

export default{
    alreadyLogin,getUserInfo,setUserInfo
}

然后在main.js配置:


import userGlobal from '@/util/userGlobal.js'
Vue.prototype.$userGlobal = userGlobal

结语:

完成该项目。其中的心酸历程当然也是一言难尽,每天10小时的超负荷工作… 以及刚开始写的时候电脑硬盘损坏,造成我是数据丢失。所以备份还是挺重要的。vue的组件使用起来也很舒服。便是以后开发项目的首选了。

发布了63 篇原创文章 · 获赞 149 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/huijiaaa1/article/details/104633749
今日推荐