在Vue3中,如何分别展示Vant库中的Button组件、Swipe滑动组件、Form表单组件、Grid网格组件、TabBar导航栏组件以及Tab选项卡组件的基本用法示例代码?
时间: 2024-11-27 10:23:27 浏览: 3
vant侧边导航栏SideBar
在 Vue3 中使用 Vant 库,首先需要安装依赖,可以使用 `npm` 或 `yarn` 来安装:
```bash
npm install vant @vue/cli-plugin-vant
# 或者
yarn add vant vue-cli-plugin-vant
```
然后在 `.vue` 文件中引入并使用这些组件:
### Button组件
```html
<template>
<v-button type="primary" @click="handleClick">点击我</v-button>
</template>
<script setup>
import { VButton } from 'vant';
const handleClick = () => {
console.log('Button clicked');
};
</script>
```
### Swipe滑动组件
```html
<template>
<v-swipe v-model="show">
<v-swipe-item slot="item" @click="handleSwipe">
<div>滑动项1</div>
</v-swipe-item>
<!-- 添加更多滑动项 -->
</v-swipe>
</template>
<script setup>
import { VSwipe, VSwipeItem } from 'vant';
let show = false;
const handleSwipe = (index) => {
// 根据 index 更新显示状态
};
</script>
```
### Form表单组件
```html
<template>
<v-form ref="form" :model="formData">
<v-input name="name" placeholder="请输入名字"></v-input>
<!-- 添加其他输入字段 -->
<v-btn type="primary" @submit.prevent="submitForm">提交</v-btn>
</v-form>
</template>
<script setup>
import { useForm } from 'vant';
import { ref } from 'vue';
const formData = ref({ name: '' });
const { register, handleSubmit } = useForm();
// 提交表单
async function submitForm() {
try {
await handleSubmit();
console.log('表单提交成功', formData.value);
} catch (error) {
console.error('表单验证错误', error);
}
}
</script>
```
### Grid网格组件
```html
<template>
<v-grid :columns="4" :gutter="16">
<v-cell :span="8" style="background-color: lightblue;">格子1</v-cell>
<!-- 添加更多格子 -->
</v-grid>
</template>
<script setup>
import { VGrid, VCell } from 'vant';
const columns = 4;
const gutter = 16;
</script>
```
### TabBar导航栏组件
```html
<template>
<v-tabsbar fixed>
<v-tab :title="tab.title" v-for="(tab, index) in tabs" :key="index" @click="selectTab(index)">
{{ tab.content }}
</v-tab>
</v-tabsbar>
</template>
<script setup>
import { VTabsbar, VTab } from 'vant';
const tabs = [
{ title: '选项卡A', content: '内容A' },
{ title: '选项卡B', content: '内容B' },
];
const selectedTabIndex = ref(0);
function selectTab(index) {
selectedTabIndex.value = index;
}
</script>
```
### Tab选项卡组件
```html
<template>
<v-tabs :value="activeIndex" @change="handleChange">
<v-tab :label="tab.name" v-for="(tab, index) in tabs" :key="index">{{ tab.content }}</v-tab>
</v-tabs>
</template>
<script setup>
import { VTabs, VTab } from 'vant';
const tabs = [
{ name: '选项卡1', content: '这是第一个选项卡的内容' },
{ name: '选项卡2', content: '这是第二个选项卡的内容' },
];
const activeIndex = ref(0);
function handleChange(index) {
console.log(`当前选中:${tabs[index].content}`);
}
</script>
```
阅读全文