vue3中watch的应用(登录时按钮是否禁用)

场景:当用户将账号与密码都输入后,登录按钮才可以使用,否则为禁用。

利用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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值