本代码旨在提供一个复选框组件,用于在 Vue.js 应用程序中选择多个选项。此组件非常适合用于创建调查问卷、过滤列表或自定义表单。
该组件具有以下基本功能:
v-model
绑定,轻松跟踪所选选项组件模板定义了组件的结构和样式。在本例中,模板包含一个包含标题、按钮和复选框列表的容器。
<template>
<div class="flex flex-col items-center justify-center min-h-screen bg-gray-100">
<div class="w-full max-w-md p-4 mx-auto bg-white rounded-md shadow-md">
<div class="flex items-center justify-between mb-4">
<h2 class="text-xl font-semibold text-gray-700">
Click the diving features you want
</h2>
<div class="flex items-center space-x-2">
<button
class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded-md"
>
Solo Diving
</button>
<button
class="px-4 py-2 text-sm font-medium text-white bg-green-500 rounded-md"
>
Team Diving
</button>
<button
class="px-4 py-2 text-sm font-medium text-white bg-red-500 rounded-md"
>
Family Diving
</button>
</div>
</div>
<div class="grid grid-cols-1 gap-4">
<div class="flex items-center justify-between">
<label class="text-sm font-medium text-gray-700">Solo Diving</label>
<input
type="checkbox"
class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
</div>
<div class="flex items-center justify-between">
<label class="text-sm font-medium text-gray-700">Team Diving</label>
<input
type="checkbox"
class="w-4 h-4 text-green-600 border-gray-300 rounded focus:ring-green-500"
/>
</div>
<div class="flex items-center justify-between">
<label class="text-sm font-medium text-gray-700">Family Diving</label>
<input
type="checkbox"
class="w-4 h-4 text-red-600 border-gray-300 rounded focus:ring-red-500"
/>
</div>
</div>
<div class="mt-4">
<button
class="w-full px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded-md"
>
Continue
</button>
</div>
</div>
</div>
</template>
组件逻辑使用 Vue.js 的 setup
函数来定义。在这个函数中,我们使用 ref
钩子来创建三个可变状态,它们对应于每个复选框的状态。
import { ref } from 'vue'
const soloDiving = ref(false)
const teamDiving = ref(false)
const familyDiving = ref(false)
我们在复选框输入上使用 Vue.js 的 v-model
绑定,将复选框的状态绑定到对应的可变状态。
<input
type="checkbox"
class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
v-model="soloDiving"
/>
我们使用 CSS 样式来定义组件的外观,并使用 Vue.js 的响应式特性来处理用户的交互。例如,当用户单击复选框时,对应的可变状态会更新,并且复选框的样式会相应地更改。
.grid {
display: grid;
}
开发此组件的过程加深了我对 Vue.js 中状态管理和响应式编程的理解。我还了解了如何使用 v-model
绑定来轻松地连接组件逻辑和用户界面。
未来,此组件可以进一步扩展和优化,例如: