十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Vue 进阶实战:事件修饰符、表单控制、购物车与 Ajax 请求

Vue 进阶实战:事件修饰符、表单控制、购物车与 Ajax 请求 一、昨日内容回顾上一节学习了 Vue 的数据绑定、条件渲染、列表渲染、事件监听和v-model。本节继续使用 Vue 2 示例重点补充 JavaScript 的箭头函数、循环方式、事件修饰符、表单控件以及前端通过 Ajax 请求后端接口的方法。二、ES6 箭头函数箭头函数是 ES6 提供的函数简写形式适合编写短小的回调函数。它可以省略function只有一个参数时还可以省略参数括号只有一个表达式时可以省略大括号和return。// 普通函数functionadd(a,b){returnab}// 箭头函数的几种写法constsayHello(){console.log(hello)}constsquarenn*nconstsum(a,b)absayHello()console.log(square(4))console.log(sum(4,6))箭头函数没有自己的this、arguments和prototype。其中最重要的是this箭头函数会捕获定义位置外层作用域的this不会因为调用方式改变。Vue 的methods建议使用普通方法让 Vue 正确绑定组件实例在方法内部作为回调时箭头函数可以方便地继续使用外层的this。newVue({data:{search:,words:[vue,react,angular]},methods:{filterWords(){// filter 的回调使用箭头函数可以直接访问外层方法的 this。returnthis.words.filter(wordword.includes(this.search))}}})三、JavaScript 常见循环不同循环适合不同场景。for可以控制下标和步长for...in遍历对象属性名for...of遍历可迭代对象中的值forEach适合对数组的每一项执行操作。constnumbers[3,4,5]// 传统 for可以使用下标、break 和 continue。for(leti0;inumbers.length;i){console.log(i,numbers[i])}// for...in数组中得到下标对象中得到属性名。for(constindexinnumbers){console.log(index,numbers[index])}constuser{name:lqz,age:19}for(constkeyinuser){console.log(key,user[key])}// for...of得到数组、字符串等可迭代对象的值。for(constvalueofnumbers){console.log(value)}// forEach参数依次是 value、index、array。numbers.forEach((value,index){console.log(index,value)})普通对象不是可迭代对象不能直接使用for...of。如果需要以键值对形式遍历可以使用Object.entries(user)Vue 模板中的v-for则可以直接遍历对象。Object.entries(user).forEach(([key,value]){console.log(key,value)})四、事件修饰符Vue 事件修饰符可以把常见的 DOM 事件处理写在模板中减少手动调用event.stopPropagation()或event.preventDefault()的代码。修饰符作用.stop阻止事件继续冒泡.self只有点击当前元素本身时才处理.prevent阻止浏览器默认行为.once事件只触发一次.capture使用捕获阶段监听事件dividappdivclasspanelclickparentClickbuttonclick.stopbuttonClick点击后不触发父元素/button/divdivclasspanelclick.selfselfClickbuttonclickchildClick点击按钮不会触发 selfClick/button/divahrefhttps://example.comclick.preventlinkClick暂不跳转/abuttonclick.oncepay只能点击一次/button/div.self与.stop的含义不同.stop是阻止事件向上冒泡.self是判断事件目标是否就是当前元素。修饰符只应处理交互行为权限、支付等关键逻辑仍必须在后端再次校验。五、按键修饰符键盘事件可以使用.enter、.esc、.tab、.delete、.up、.down、.left和.right等修饰符也可以监听系统组合键。dividappinputv-modelkeywordkeyup.entersearchplaceholder输入关键词后按回车buttonclicksearch搜索/button/divscriptnewVue({el:#app,data:{keyword:},methods:{search(){console.log(搜索,this.keyword)}}})/script相比直接使用数字 keyCode语义化的.enter更容易理解也不依赖不同浏览器的键码差异。需要读取更多键盘信息时可以在方法参数中接收原生事件对象。六、表单控件与 v-modelv-model会根据控件类型选择合适的属性和事件文本框通常对应字符串单个复选框对应布尔值多个同名复选框对应数组单选框对应字符串或数字。dividappp用户名inputv-model.trimusername/pp密码inputtypepasswordv-modelpassword/plabelinputtypecheckboxv-modelremember记住登录/labelp爱好/plabelinputtypecheckboxv-modelhobbiesvalue篮球篮球/labellabelinputtypecheckboxv-modelhobbiesvalue足球足球/labellabelinputtypecheckboxv-modelhobbiesvalue游泳游泳/labelp性别/plabelinputtyperadiov-modelgendervalue男男/labellabelinputtyperadiov-modelgendervalue女女/labelbuttonclicksubmit提交/button/divscriptnewVue({el:#app,data:{username:,password:,remember:false,hobbies:[],gender:},methods:{submit(){console.log({username:this.username,password:this.password,remember:this.remember,hobbies:this.hobbies,gender:this.gender})}}})/scriptv-model只负责在前端同步数据不代表表单已经安全。登录、注册等数据仍需要后端校验密码也不能明文保存。七、购物车综合案例购物车同时练习了v-for、v-model、事件、计算总价和全选逻辑。选中商品数组保存的是商品对象数量变化后总价会根据当前选中项重新计算。dividapptabletheadtrth商品/thth单价/thth数量/thth选择/th/tr/theadtbodytrv-for(item, index) in goods:keyitem.idtd{{ item.name }}/tdtd{{ item.price }} 元/tdtdbuttonclickdecrease(item)-/button{{ item.number }}buttonclickitem.number/button/tdtdinputtypecheckboxv-modelselectedGoods:valueitem/td/tr/tbody/tablelabelinputtypecheckboxv-modelcheckAllchangetoggleAll全选/labelp总价{{ totalPrice }} 元/p/divscriptnewVue({el:#app,data:{goods:[{id:1,name:脸盆,price:9,number:2},{id:2,name:水杯,price:19,number:1},{id:3,name:电脑,price:6999,number:1}],selectedGoods:[],checkAll:false},computed:{totalPrice(){returnthis.selectedGoods.reduce((total,item)totalitem.price*item.number,0)}},watch:{selectedGoods:{deep:true,handler(value){this.checkAllvalue.lengththis.goods.length}}},methods:{toggleAll(){this.selectedGoodsthis.checkAll?this.goods.slice():[]},decrease(item){if(item.number1)item.number--}}})/script总价属于“由已有数据计算出来的值”因此使用computed比每次在模板中调用方法更合适依赖不变时会缓存结果。全选状态与单个商品选择状态互相影响使用深度监听可以在选择数组变化后同步更新全选框。八、v-model 修饰符v-model修饰符用于改变同步时机或数据类型.lazy从input事件改为在change后同步。.number尝试把输入值转换为数字。.trim去除输入字符串首尾空格。dividappinputv-model.lazytextplaceholder失去焦点后同步inputv-model.numberamountplaceholder尝试转换数字inputv-model.trimnameplaceholder去除首尾空格p{{ text }} / {{ amount }} / {{ name }}/p/div.number不是严格的类型校验空字符串或无法转换的输入仍可能保留原值。金额、年龄等数据在提交前仍应在后端进行类型和范围校验。九、Ajax 与接口请求Ajax 泛指浏览器在页面不刷新时与服务器交换数据的方式。早期可以直接使用XMLHttpRequestjQuery 对它做了封装现代项目更常使用fetch或 axios。axios 提供统一的请求配置、拦截器、错误处理和 JSON 转换适合在 Vue 项目中集中管理接口。1. axios 请求示例dividappbuttonclickloadUser加载用户信息/buttonp用户名{{ user.username }}/pp年龄{{ user.age }}/pp性别{{ user.gender }}/ppv-iferrorclasserror{{ error }}/p/divscriptsrchttps://unpkg.com/axios/dist/axios.min.js/scriptscriptnewVue({el:#app,data:{user:{username:,age:,gender:},error:},methods:{asyncloadUser(){this.errortry{constresponseawaitaxios.get(http://127.0.0.1:8888/info)// axios 的响应体位于 response.data。this.userresponse.data}catch(error){console.error(error)this.error用户信息加载失败请稍后重试}}}})/script使用async/await可以让异步流程更接近同步代码try/catch用于处理网络失败和非预期响应。实际项目还应处理加载中状态、HTTP 状态码和接口业务错误码。2. Flask 接口示例fromflaskimportFlask,jsonify appFlask(__name__)app.get(/info)definfo():responsejsonify({username:张三,age:99,gender:男,})# 仅用于演示生产环境应限制为明确的前端域名。response.headers[Access-Control-Allow-Origin]http://localhost:8080returnresponseif__name____main__:app.run(port8888)当前端和后端的协议、域名或端口不同时浏览器会执行同源策略检查服务端需要通过 CORS 响应头明确允许来源。Access-Control-Allow-Origin: *不适合携带凭证的请求也不建议在生产环境无限制开放。十、总结与练习箭头函数适合回调重点理解它没有自己的thisVue 的方法本身不要随意改成箭头函数。for...in遍历键for...of遍历值数组还可以使用forEach、map、filter等方法。事件修饰符负责冒泡、默认行为和触发次数按键修饰符让键盘交互更直观。复选框的v-model可以绑定布尔值或数组购物车应使用唯一key、计算属性和清晰的全选逻辑。axios 适合 Vue 项目中的接口请求跨域问题需要由后端 CORS 配置配合解决。
返回列表