2.5示例:实现用户登录页面
使用Vue来构建一个简单的登录页面,借助Vue的单双向绑定和条件渲染功能,完成登录需求则会非常容易。创建一个login.html文件,如例2-2所示。
【例2-2】用户登录页面
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<!-- 引入vue文件 -->
<script src="https://unpkg.com/vue@next"></script>
<title>登录</title>
</head>
<body>
<div id="app" style="text-align: center;">
<h1>{{title}}</h1>
<div v-if="noLogin">账号:<input v-model="userName" type="text"></div>
<div
v-if="noLogin">密码:<input
v-model="password" type="text"></div>
<div v-on:click="click"
style="border-radius: 30px ;width: 100px;
margin: 20px auto; color:
white;background-color: blue;">{{buttonTitle}}</div>
</div>
<script>
const vm=Vue.createApp({
data(){
return{
title:"欢迎您,未登录",
noLogin:true,
userName:'',
password:'',
buttonTitle:"登录"
}
},
methods:{
click(){
if(this.noLogin){
this.login()
}else{
this.logout()
}
},
//登录
login(){
if(this.userName.length>0&&this.password.length>0){
alert(`userName:${this.userName}
password:${this.password}`)
this.noLogin=false
this.title=欢迎您:${this.userName}
this.buttonTitle="注销"
this.userName=""
this.userName=""
}else{
alert("请输入账号和密码")
}
},
//退出
logout(){
this.noLogin=true
this.title=欢迎您:未登录
this.buttonTitle="登录"
}
}
}).mount("#app");
</script>
</body>
</html>
在上面的代码中v-if是Vue提供的条件渲染功能,其指定的变量如果值为true,则渲染这个元素,否则不渲染。v-model用来进行双向绑定,当输入框中的文字变化时,其会将变化同步到绑定的变量上,同样,当我们对变量的值进行改变时,输入框中的文本会对应变化。
运行上面代码,未登录时效果如图2-10所示。当输入用户名和密码登录后,效果如图2-11所示。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。