#VueFormSub.js(实现双向绑定主要代码) //实现取值 var VueFormSub = function(formid){ this.$form = ($("#" + formid).length !=0)?$("#" + formid):$("."+formid); var models = $("*[v-model != '']", this.$form); var vueData = {}; $.each(models,function(idx,dom){ var key = $(dom).attr("name"); if (undefined != key){ var dValue = $(dom).val(); $(dom).val(dValue); var beanName = key.split("_"); if(beanName.length < 2){ vueData[beanName] = dValue; vueData[beanName] = $("input[type='radio'][name='"+key+"']:checked").val(); }else{ if(vueData[beanName[0]] == undefined){ vueData[beanName[0]] = {}; }else{ if($(dom).attr("type") == "radio"){ var tempVal = $("input[type='radio'][name='"+key+"']:checked").val(); vueData[beanName[0]][beanName[1]] = tempVal; }else{ vueData[beanName[0]][beanName[1]]=dValue; } } } } }); return vueData; }; #初始化Vue表单数据(可以只传入initDate数据源,formid需要绑定的dom) VueFormSub.initVue = function(initDate,formid,httpMethod, url, params){ if(initDate instanceof Object){ /*if(initDate.length !=0){}*/ var initJson = VueFormSub.ObjConvert(initDate); new Vue({ el : ($("#"+formid).length != 0)?'#'+formid:'.'+formid, data : initJson }); }else{ if (httpMethod != "get" && params && typeof (params) == "object"){ params = JSON.stringify(params); } if(params!= null){ params.rs = Math.random(); }else{ params = {'rs':Math.random()}; } $.ajax({ type: httpMethod, url: "/cxh" + url, data: params, cache:false, async: true, contentType: 'application/json', dataType: 'json', success: function (returnData) { if(returnData.length != 0){ var vueDate = VueFormSub.ObjConvert(returnData); new Vue({ el:($("#"+formid).length != 0)?'#'+formid:'.'+formid, data : vueDate }); } } }); } }; #对需要绑定的对象进行解析成Vue支持的格式 VueFormSub.ObjConvert = function(dataObj){ var json = {}; $.each(dataObj,function(id,param){ if(param instanceof Object){ $.each(param, function(rid,rparam){ if(rparam instanceof Object){ json[id] = VueFormSub.ObjConvert(param); }else{ json[id+"_"+rid] = rparam; } }); }else{ json[id]=param; } }); return json; };
#使用实例 <script> #初始化数据data var initVue = { RegistInfo_name : 'legend', RegistInfo_user : '龙军', RegistInfo_phone : '1008611', RegistInfo_chakan_money : '100', RegistInfo_rescue_money : '1000', address : '广东省汕头市潮南区', RegistInfo_chakan_data : '2017-5-7', RegistInfo_say : '这个只是测试用的', remark : '龙军用来测试的', Prplregist_name : '林总', Prplregist_user : '林老板', Prplregist_phone : '10010', Prplregist_chakan_money : '一万块', Prplregist_rescue_money : '一个亿', RegistInfo_radio : "Runoob", RegistInfo_selected : "google", RegistInfo_helongjun : "helongjun", testOne:"" }; //初始化Vue表单 VueFormSub.initVue(initVue,"container-fluid"); //返回按钮单击 function getInputVal(){ //调用自动表单封装 var resultVal = new VueFormSub("container-fluid"); console.log(resultVal); } #注意:input表单中的name属性必须指定,最好和input表单中的v-model的值一样 <script>
最终效果:
以上这篇Vue.js实现双向数据绑定方法(表单自动赋值、表单自动取值)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章: