Vue3 小功能记录:密码的显示与隐藏功能
Vue3 小功能记录:密码的显示与隐藏功能
步骤一:创建组件
在 src/components 目录下创建一个新的组件文件 PasswordToggle.vue:
<template><div class="password-toggle"><input :type="inputType" v-model="password" placeholder="请输入密码" /><button @click="togglePasswordVisibility">{{ buttonLabel }}</button></div>
</template><script>
import { ref, computed } from 'vue';export default {setup() {// 定义响应式数据const password = ref('');const isPasswordVisible = ref(false);// 计算属性:动态切换输入框类型const inputType = computed(() => (isPasswordVisible.value ? 'text' : 'password'));// 计算属性:动态切换按钮文本const buttonLabel = computed(() => (isPasswordVisible.value ? '隐藏' : '显示'));// 方法:切换密码显示状态const togglePasswordVisibility = () => {isPasswordVisible.value = !isPasswordVisible.value;};// 返回数据和方法供模板使用return {password,isPasswordVisible,inputType,buttonLabel,togglePasswordVisibility,};},
};
</script><style scoped>
.password-toggle {display: flex;align-items: center;
}input {margin-right: 10px;padding: 5px;
}button {padding: 5px 10px;cursor: pointer;
}
</style>
步骤二:在主应用中使用组件
打开 src/App.vue 文件,将 PasswordToggle 组件引入并使用:
<template><div id="app"><h1>密码显示与隐藏示例</h1><PasswordToggle /></div>
</template><script>
import PasswordToggle from './components/PasswordToggle.vue';export default {components: {PasswordToggle,},
};
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>
代码解析
- 组合式 API:
- 使用
ref定义响应式数据password和isPasswordVisible。 - 使用
computed定义计算属性inputType和buttonLabel,根据isPasswordVisible的值动态返回输入框类型和按钮文本。
- 使用
- 模板部分:
input元素的type属性绑定了inputType计算属性,根据isPasswordVisible的值动态切换为'text'或'password'。button元素的文本绑定了buttonLabel计算属性,根据isPasswordVisible的值动态显示'显示'或'隐藏'。button元素的@click事件绑定了togglePasswordVisibility方法,用于切换isPasswordVisible的值。
- 方法部分:
togglePasswordVisibility是一个简单的方法,用于切换isPasswordVisible的值。
