Vue学习笔记(二):实际项目中运用Vue进行页面渲染、操作数据

说明:本篇博客主要讲述实际项目中如何使用Vue来进行页面渲染,以及对数据进行一些增改操作:

一。页面数据渲染

1.实体类:

package cn.com.do1.miner.model;

import com.alibaba.fastjson.annotation.JSONField;

import java.util.Date;

/**
 * 矿机VO类
 * @author : zhongkaisheng
 * @date : 2020/6/12 10:14
 */
public class MinerVO {

    /*
     * id
     */
    private Integer id;

    /*
     *商品名称
     */
    private String name;

    /*
     *商品库存
     */
    private Integer count;

    /*
     *总算力
     */
    private String speed;

    /*
     *开售时间
     */
    @JSONField(format="yyyy-MM-dd")
    private Date saleTime;

    /*
     *开机时间
     */
    @JSONField(format="yyyy-MM-dd")
    private Date startTime;

    /*
     *购买价格
     */
    private Double price;

    /*
     *所属类型(0标识购买,1标识租赁,2标识历史)
     */
    private Integer productType;

    /*
     *租赁期限(0三个月,1六个月,2一年)
     */
    private String term;

    /*
     *图片
     */
    private String image;

    /*
     *前台存放图片路径
     */
    private String imageFront;

    /*
     *删除标记
     */
    private Integer isDelete;

    /*
     *创建时间
     */
    private Date createTime;

    /*
     *修改时间
     */
    private Date updateTime;

    /*
     *图片base64编码
     */
    private String base64;



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public String getSpeed() {
        return speed;
    }

    public void setSpeed(String speed) {
        this.speed = speed;
    }

    public Date getSaleTime() {
        return saleTime;
    }

    public void setSaleTime(Date saleTime) {
        this.saleTime = saleTime;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Integer getProductType() {
        return productType;
    }

    public void setProductType(Integer productType) {
        this.productType = productType;
    }

    public String getTerm() {
        return term;
    }

    public void setTerm(String term) {
        this.term = term;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public Integer getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(Integer isDelete) {
        this.isDelete = isDelete;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getImageFront() {
        return imageFront;
    }

    public void setImageFront(String imageFront) {
        this.imageFront = imageFront;
    }

    public String getBase64() {
        return base64;
    }

    public void setBase64(String base64) {
        this.base64 = base64;
    }

    @Override
    public String toString() {
        return "Miner{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", count=" + count +
                ", speed='" + speed + '\'' +
                ", saleTime=" + saleTime +
                ", startTime=" + startTime +
                ", price=" + price +
                ", productType=" + productType +
                ", term='" + term + '\'' +
                ", image='" + image + '\'' +
                ", imageFront='" + imageFront + '\'' +
                ", isDelete=" + isDelete +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", base64='" + base64 + '\'' +
                '}';
    }
}

package cn.com.do1.coupon.model;

import com.alibaba.fastjson.annotation.JSONField;

import java.util.Date;

/**
 * 优惠券VO
 * @author : zhongkaisheng
 * @date : 2020/6/12 14:51
 */
public class CouponVO {

    /*
     id
      */
    private Integer id;

    /*
    优惠券名称
     */
    private String name;

    /*
    优惠券优惠价格
     */
    private String couponPrice;


    /*
    发放时间
     */
    @JSONField(format="yyyy-MM-dd")
    private Date createTime;

    /*
    过期时间
     */
    @JSONField(format="yyyy-MM-dd")
    private Date endTime;

    /*
    优惠券状态
     */
    private Integer status;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCouponPrice() {
        return couponPrice;
    }

    public void setCouponPrice(String couponPrice) {
        this.couponPrice = couponPrice;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Coupon{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", couponPrice='" + couponPrice + '\'' +
                ", createTime=" + createTime +
                ", endTime=" + endTime +
                ", status=" + status +
                '}';
    }
}

2.前端页面主要代码:

<!--
	支付步骤1-paySatus_step_order
-->
<div class="paySatus_step paySatus_step_order">
	<div class="paySatus">
		<div class="paySatus_inner paySatus_first">
			<span class="paySatus_buy">订单详情</span>
			<span class="paySatus_pay">订单支付</span>
			<span class="paySatus_payend">支付完成</span>
		</div>
	</div>
	<div class="payDetail">
		<div class="orderMsg">
			订单详情
			<span>请尽快付款完成交易,<b class="countTime">00:18:29</b> 后订单将自动取消</span>
		</div>
		<table border="0" cellspacing="0" cellpadding="0" width="100%" class="table_layer infoTable" >
			<tbody>
				<tr>
					<td class="td_f8" width="150">商品名称</td>
					<input type="hidden" id="miner_name" :value="miner.name"/>
					<td><span>{{miner.name}}</span></td>
				</tr>	
				<tr>
					<td class="td_f8" width="150">购买数量</td>
					<input type="hidden" id="miner_count" :value="buyCount"/>
					<td><span>{{buyCount}}</span></td>
				</tr>	
				<tr>
					<td class="td_f8" width="150">价格/单价</td>
					<input type="hidden" id="miner_price" :value="miner.price"/>
					<td><span class="dpriceMoney">{{miner.price}}(元)</span></td>
				</tr>	
				<tr>
					<td class="td_f8" width="150">起售时间</td>						
					<td><span>{{miner.saleTime}}</span></td>
				</tr>
				<tr>
					<td class="td_f8" width="150">订单编号</td>
					<input type="hidden" id="order_no" :value="orderNo"/>
					<td><span >{{orderNo}}</span></td>
				</tr>	
				<tr>
					<td class="td_f8" width="150">总算力</td>
					<input type="hidden" id="miner_speed" :value="miner.speed"/>
					<td><span>{{miner.speed}}</span></td>
				</tr>	
				<tr>
					<td class="td_f8" width="150">订单总价</td>
					<input type="hidden" id="total_price" :value="miner.price*buyCount"/>
					<td><span class="dpriceCountMoney">{{miner.price*buyCount}}(元)</span></td>
				</tr>	
				<tr>
					<td class="td_f8" width="150">开机时间</td>						
					<td><span>{{miner.startTime}}</span></td>
				</tr>		
				
			</tbody>
		</table>
		<div class="cardPacel">
			<input type="hidden" id="payment" :value="miner.price*buyCount-favorablePrice"/>
			<input type="hidden" id="reduced_price" :value="favorablePrice"/>
			<h3 class="odTitles"><i class="kpoint"></i><span>该订单您有<b class="odNums">{{num}}</b>张优惠券可以使用</span></h3>
			<div class="cardPacelBox">
				<ul>
					<li v-for="c,index in couponList" @click="get_text(index)">
						<div class="card_item">
							<div class="fl card_money">
								<h3>{{c.couponVO.couponPrice}}</h3>
								<input type="hidden" :id="'price'+index" :value="c.couponVO.couponPrice"/>
								<p>CNY</p>
							</div>
							<div class="fl card_info">
								<div class="card_info_inner">
									<h3>{{c.couponVO.name}}</h3>
									<h4>适用机型:<span>通用</span></h4>
									<p>1张</p>
								</div>												
							</div>
							<div class="fr card_staus" >
								<input type="hidden" :id="'status'+index" value="可使用"/>
								<b>可使用</b>
							</div>
						</div>
					</li>
				</ul>
			</div>
			<input type="radio" id="agree" style="margin-left: 450px"/>同意<a href="http://47.92.156.154:8230/static/union/buy.pdf" style="color: blue">《超算服务器购买委托合同》</a><a href="http://47.92.156.154:8230/static/union/maintain.pdf" style="color: blue">《超算服务器维护委任合同》</a>
		</div>
	</div>
	<div class="formBtnBox">
		<a class="Jcom_btn" @click.prevent="addOrder()">下一步</a>
	</div>
</div>

3.vue实例代码:

//获取页面传来的矿机id
var minerId = getQueryString('id');
//获取页面传来的矿机数量count
var minerCount=getQueryString('count');
var vue = new Vue({
	el:'#app',
	data:{
		//购买数量
		buyCount:0,
		//矿机实体信息
		miner:[],
		//用户优惠券列表
		couponList:[],
		//优惠券个数
		num:0,
		//优惠券优惠价格
		favorablePrice:0,
		//订单编号
		orderNo:0,
	},
	created(){
		//引入首页导航栏
		$('.indextophtml').load('../common/_tab.html');
		this.buyCount=minerCount;
		// 获取矿机商品数据
		this.$http
				.get('../miner/getMinerById/'+minerId)
				.then((resp) => {
					var respData = resp.data;
					if(respData.code == 0) {
						// 读取表单数据
						this.miner = respData.data.minerVO;
					} else {
						alert('查询数据失败!');
					}
	});
		// 获取优惠券列表
		this.$http
				.get('../coupon/getCoupons')
				.then((resp) => {
					var respData = resp.data;
					if(respData.code == 0) {
						// 读取表单数据
						this.couponList = respData.data.couponVOList;
						this.num=respData.data.num;
					} else {
						alert('查询数据失败!');
					}
				});
		// 获取订单编号
		this.$http
				.get('../order/getOrderNo')
				.then((resp) => {
					var respData = resp.data;
					if(respData.code == 0) {
						// 读取表单数据
						this.orderNo = respData.data.orderNo;
					} else {
						alert('返回订单编号失败!');
					}
				});
	},
	})

4.后台相应接口代码:

 /**
     * 根据id得到矿机信息
     * @param id
     * @return
     */
    @RequestMapping("getMinerById/{id}")
    @ResponseBody
    public Object getMinerById(@PathVariable Integer id){
        //初始化json对象
        JSONObject jsonObject=new JSONObject();
        //根据id拿到id信息
        MinerVO minerVO=minerService.getMinerById(id);
        //存入josn对象
        jsonObject.put("minerVO",minerVO);
        //返回json对象
        return Result.ok(jsonObject);

    }
/**
     * 根据用户id以及时间戳生成一个订单编号
     * @return
     */
    @RequestMapping("getOrderNo")
    @ResponseBody
    public Object getOrderNo(HttpServletRequest request){
        JSONObject jsonObject=new JSONObject();
        //获取session中的对象
        MemberVO memberVO= (MemberVO) request.getSession().getAttribute("member");
        Date date = new Date();
        //格式日期转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        //根据用户id以及时间戳生成订单编号
        String orderNo=memberVO.getId()+sdf.format(date);
        jsonObject.put("orderNo",orderNo);

        return Result.ok(jsonObject);
    }
/**
     * 得到用户下所有优惠券信息
     * @param request
     * @return
     */
    @RequestMapping("getCoupons")
    @ResponseBody
    public Object getCoupons( HttpServletRequest request){
        Integer num=0;
        //初始化json对象
        com.alibaba.fastjson.JSONObject jsonObject=new JSONObject();
        //得到session中存的用户信息
        //MinerVO minerVO= (MinerVO) request.getSession().getAttribute("member");
        //根据用户id以及优惠券id查找优惠券信息
        List<MemberCouponVO> couponVOList =couponService.getCoupondsByMemberId(22);
        if(couponVOList!=null){
            //得到优惠券张数
            num=couponVOList.size();
        }
        //存入josn对象
        jsonObject.put("couponVOList",couponVOList);
        jsonObject.put("num",num);
        //返回json对象
        return Result.ok(jsonObject);
    }

5.效果图:
在这里插入图片描述
在这里插入图片描述
6.注意点:

  1. Vue实例中,created()下所包含的方法是实例初始化时就执行,类似与JQuery中的$(document).ready(function(){})初始化函数一样,在其中若需要用到data中定义的变量,用this+“.”+变量名就能访问:
    在这里插入图片描述
  2. Vue也有和JQuery中Ajax请求类似的调用后台接口的方法:
    在这里插入图片描述
  3. 后台接口使用Result.ok()返回状态码:
    在这里插入图片描述
    在这里插入图片描述
  4. josn格式传输实体类对象时,时间属性需要做类型转换:
    在这里插入图片描述

二。增加修改数据

1.实体类:

package cn.com.do1.user.model;

import java.util.Date;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;

import cn.com.do1.common.Constants;
import cn.com.do1.common.annotation.Condition;
import cn.com.do1.common.enumeration.ConditionType;
import cn.com.do1.common.model.BaseVO;
import cn.com.do1.common.util.annotation.CopyProperty;
import cn.com.do1.core.cache.annotation.ReadForCache;
import cn.com.do1.core.resolver.annotation.AliasFor;
import cn.com.do1.person.model.PersonVO;
import cn.com.do1.user.pojo.User;

public class UserVO extends BaseVO<User, UserVO> {
	private static final long serialVersionUID = -265611340684375445L;
	private String userId;
	@NotBlank(message = "用户ID不能为空!")
	@Length(max = 100, message = "用户ID长度不能大于100位!")
	private String userName;
	private String password;
	@NotBlank(message = "用户状态不能为空!")
	@Pattern(regexp = Constants.Regex.status, message = "用户状态格式不正确!")
	private String status;
	private String statusName;
	private Date lastLoginTime;
	private Integer isInternal;
	private String refAurthCode;
	private Integer refType;
	@NotNull
	@Valid
	private PersonVO person = new PersonVO();
	@AliasFor(bindObject = "person")
	private String personName;
	@AliasFor(bindObject = "person")
	private String email;
	@AliasFor(bindObject = "person")
	private String mobleNum;

	@Condition(type = ConditionType.Equal)
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	@CopyProperty
	@Condition(type = ConditionType.Equal)
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@CopyProperty
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public Date getLastLoginTime() {
		return lastLoginTime;
	}

	public void setLastLoginTime(Date lastLoginTime) {
		this.lastLoginTime = lastLoginTime;
	}

	public Integer getIsInternal() {
		return isInternal;
	}

	public void setIsInternal(Integer isInternal) {
		this.isInternal = isInternal;
	}

	public String getRefAurthCode() {
		return refAurthCode;
	}

	public void setRefAurthCode(String refAurthCode) {
		this.refAurthCode = refAurthCode;
	}

	public Integer getRefType() {
		return refType;
	}

	public void setRefType(Integer refType) {
		this.refType = refType;
	}

	public PersonVO getPerson() {
		return person;
	}

	public void setPerson(PersonVO person) {
		this.person = person;
	}

	public String getPersonName() {
		return personName;
	}

	public void setPersonName(String personName) {
		this.personName = personName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMobleNum() {
		return mobleNum;
	}

	public void setMobleNum(String mobleNum) {
		this.mobleNum = mobleNum;
	}

	@ReadForCache(fsType = "STAT", srcFieldName = "status")
	public String getStatusName() {
		return statusName;
	}

	public void setStatusName(String statusName) {
		this.statusName = statusName;
	}
	
	public UserVO clearPassword() {
		setPassword(null);
		return this;
	}

}

2.前端页面主要代码:

<div class="editBox">
	<h3 class="edit_title">用户基本信息<a href="javascript:;" class="editShow"></a></h3>
	<div class="editBar clearfix">
		<div class="dBar clearfix">
			<dl class="flex100">
				<dt>用户编号</dt>
				<dd>
					<div class="iSBox">
						<input type="text" v-model="model.userName" class="ipt" />
					</div>
				</dd>
			</dl>
			<dl class="flex100">
				<dt>用户姓名</dt>
				<dd>
					<div class="iSBox">
						<input type="text" v-model="model.person.personName" class="ipt" />
					</div>
				</dd>
			</dl>
			<dl class="flex100">
				<dt>用户联系电话</dt>
				<dd>
					<div class="iSBox">
						<input type="text" v-model="model.person.mobleNum" class="ipt" />
					</div>
				</dd>
			</dl>
			<dl class="flex100">
				<dt>用户邮箱</dt>
				<dd>
					<div class="iSBox">
						<input type="text" v-model="model.person.email" class="ipt" />
					</div>
				</dd>
			</dl>
			<dl class="flex100">
				<dt>状态</dt>
				<dd>
					<div v-for="(stat, index) in stats" class="iLabel iRadio" :class="model.status===stat.fsItemCode?(index>0?'ml20 iOn':'iOn'):(index>0?'ml20':'')">
	    				<i>
	    					<input type="radio" :class="'iCheck'" name="stat" :value="stat.fsItemCode" />
	    				</i>
	    				<span>{{stat.fsItemDesc}}</span>
	    			</div>
				</dd>
			</dl>
		</div>
	</div>
</div>

3.vue实例:

/*vue定义*/
var vue = new Vue({
  el: '#app',
  data: {
	  'model': {
		  'person': {},
		  'status': '0'
	  },
	  'stats': []
  },
  methods: {
	  init() {
		  this.$http
		  	.get('/dictionary/list/STAT')
		  	.then((resp) => {
		  		var respData = resp.data;
		  		if(respData.code == 0) {
			  		this.stats = respData.data;
		  		} else {
		  			ui.alert('查询数据失败!');
		  		}
		  		$(document.body).show();
	  		});
	  },
	  submit() {
		  var stat = $('.iOn').find('input:radio').val();
		  this.model.status = stat;
		  this.$http
		  	.post('/user/_add', this._data.model)
		  	.then((resp) => {
		  		if(resp.data.code == 0) {
					//ui.alert('添加成功');
					window.location.href = "list.html";
				} else {
					ui.alert(resp.data.message);
				}
		  	});
	  },
  }
});

4.后台接口:

@PostMapping("/_add")
	public Object add(@Validated @RequestBody UserVO userVO) {
		return Result.ok(userService.saveModel(userVO));
	}

5.注意点:

  1. 表单数据增加修改直接使用v-model标签双向绑定数据:
    在这里插入图片描述
    2.后台接口要使用@Validated、@RequestBody注解来接收传输的json对象:
    在这里插入图片描述
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Keson Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值