场景:当用户将账号与密码都输入后,登录按钮才可以使用,否则为禁用。
利用vue3中的watch可以监听多个值
vue3中的watch:
watch([val1,val2,val3],([newVal1,newVal2,newVal3],[oldVal1,oldVal2,oldVal3])=>{
//一些逻辑
},{deep:true,immediate:true})
与vue2的不同:vue2的watch只能监听一个值
<template>
<div>
<p>Length: {{ textLength }}</p>
<input v-model="message" />
</div>
</template>
<script>
export default {
data() {
return {
message: '',
textLength: 0
};
},
watch: {
message(newValue, oldValue) {
this.textLength = newValue.length;
}
}
};
</script>
vue3实现登录的完整代码:
<template>
<div class="login">
<input
type="text"
name=""
class="inp"
placeholder="请输入账号"
v-model="name"
/>
<br />
<input
type="password"
name=""
class="inp"
placeholder="请输入密码"
v-model="pwd"
/>
<br />
<button class="but" :disabled="disabled" @click="login">立即登录</button>
</div>
</template>
<script>
import { reactive, ref, toRefs, watch } from "vue";
export default {
setup() {
let name = ref("");
let pwd = ref("");
let disabled = ref(true);
let isLogin = watch([name, pwd], ([newName, newPwd]) => {
if (newName.length > 0 && newPwd.length > 0) {
disabled.value = false;
} else {
disabled.value = true;
}
});
// 清除监听
let login = () => {
alert("登录成功");
isLogin();
};
return {
name,
pwd,
disabled,
login,
};
},
};
</script>
<style scoped>
.login {
width: 500px;
height: 150px;
/* 让盒子水平垂直居中 */
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
/* 盒子阴影 */
box-shadow: 2px 3px 5px rgba(30, 30, 30, 0.6);
padding: 20px;
}
.inp {
width: 100%;
height: 30px;
box-sizing: border-box;
/* margin-top: 20px; */
margin-bottom: 30px;
}
.but {
width: 100%;
background-color: #76eafc;
color: white;
border: 0;
}
.but:disabled {
background-color: darkgray;
/* 鼠标变禁用图标 */
cursor: not-allowed;
}
</style>