一:freeMarker的使用
1:java后台使用freeMarker是通過Model,將值傳給前端:
如:
@Controller
public class MobileNewsFreeMarkerController {
@RequestMapping("page/test")
public String Test(Model model,HttpServletRequest request){
//獲取項目路徑
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+""+request.getContextPath()+"/";
//將頁面路徑通過model傳給前台
model.addAttribute("basePath", basePath);
//通過HttpServletRequest 獲取url中的值,如code值
String code = request.getParameter("code");
//將獲取的code參數傳給前台
model.addAttribute("code ", code );
//頁面跳轉
return "page/test";
}
}
2:前端頁面獲取后台傳輸的值(freeMarker傳輸的值只能在html頁面獲取)
注:這里是結合vue
第一步:在js中定義vue的相關參數:
var vm = new Vue({
el: '#rrapp',
data: {
basePath:"", //項目路徑
code : "", // code參數
},
..........(vue后面內容省略)
第二步:再在頁面接收后台傳輸的值
<head>
<script type="text/javascript">
$(document).ready(function() {
<#if basePath??>
vm.basePath="${basePath}";
</#if>
<#if userId??>
vm.code ="${code }";
</#if>
});
</script>
</head>
二:使用中主要遇到的問題
1:Vue存在調用的先后順序,雖然html頁面將后台傳輸的值付給vue的data中的參數,但是在mounted中是無法使用的時候獲取的還是創建的vue的時候data中賦的值,並不會使用html賦的值:
如:
var vm = new Vue({
el: '#rrapp',
data: {
basePath: "",
code :"",
},
mounted: function () {
var _this = this;
console.log(_this.basePath);
//輸出的還是:"",並不會輸出html賦的值,所有在這里無法使用
}
2:但是在vue中methods內的方法是可以直接使用的;初始化如果需要html中傳輸的參數,可以使用以下方法:
$(function () {
vm.getData(vm.basePath,vm.code);
});
var vm = new Vue({
el: '#rrapp',
data: {
basePath: "",
code :"",
},
methods: {
getData: function (baseUrlFlag,codeFlag) {
var _this=this;
_this.basePath= baseUrlFlag;
_this.code =codeFlag;
//進行初始化業務操作!
},
}