阻止表单提交
在学习get,post时,我添加了一个阻止表单提交的代码
相关代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="vue.js"></script> </head> <body> <form id="form" action="/student" method="post"> <div> <div style="margin:10px 0">加法计算器</div> <div style="margin:10px 0">加数1:<input style="margin:0 5px" type="text" name="num1" v-model="user.num1"></div> <div style="margin:10px 0">加数2:<input style="margin:0 5px" type="text" name="num2" v-model="user.num2"></div> <button type="submit" @click="sub">提交</button> </div> <!-- <input type="submit" value="提交">--> </form> <script> const {reactive}=Vue; const user=reactive({ num1:'', num2:'' }) function sub() { if (user.num1.trim().length==0||user.num2.trim().length==0){ alert("不能为空值!"); return false; } } let form={ setup(){ return{user,sub} } } Vue.createApp(form).mount('#form'); </script> </body> </html>
为什么弹出警告后确定表单还是跳转到了/student
11
收起
正在回答
1回答
同学你好,同学可以在form表单中添加onsubmit="return sub()",并将button中的@click="sub"去掉
1 2 3 4 5 6 7 8 | < form id = "form" action = "/student" method = "post" onsubmit = "return sub()" > < div > < div style = "margin:10px 0" >加法计算器</ div > < div style = "margin:10px 0" >加数1:< input style = "margin:0 5px" type = "text" name = "num1" v-model = "user.num1" ></ div > < div style = "margin:10px 0" >加数2:< input style = "margin:0 5px" type = "text" name = "num2" v-model = "user.num2" ></ div > < button type = "submit" >提交</ button > </ div > </ form > |
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧