完整代码实现 uniapp 分类左右联动
时间: 2023-10-02 14:04:13 浏览: 53
以下是一个简单的示例代码,演示了如何在 uniapp 中实现分类左右联动效果:
```html
<template>
<view class="container">
<view class="left">
<!-- 左侧分类列表 -->
<scroll-view scroll-y="true">
<view v-for="(category, index) in categories"
:class="{ active: currentIndex === index }"
@click="handleCategoryClick(index)">
{{ category }}
</view>
</scroll-view>
</view>
<view class="right">
<!-- 右侧商品列表 -->
<scroll-view scroll-y="true">
<view v-for="(product, index) in products" :key="product.id">
<image :src="product.image" />
<view>{{ product.name }}</view>
<view>¥{{ product.price }}</view>
</view>
</scroll-view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
categories: ['水果', '蔬菜', '肉类', '海鲜'], // 左侧分类列表
products: [ // 右侧商品列表
{
id: 1,
name: '苹果',
price: 5,
image: 'https://example.com/apple.png',
category: '水果',
},
{
id: 2,
name: '香蕉',
price: 3,
image: 'https://example.com/banana.png',
category: '水果',
},
{
id: 3,
name: '西红柿',
price: 2,
image: 'https://example.com/tomato.png',
category: '蔬菜',
},
{
id: 4,
name: '鸡肉',
price: 12,
image: 'https://example.com/chicken.png',
category: '肉类',
},
{
id: 5,
name: '虾',
price: 20,
image: 'https://example.com/shrimp.png',
category: '海鲜',
},
],
currentIndex: 0, // 当前选中的分类索引
};
},
methods: {
handleCategoryClick(index) {
// 点击分类列表时更新当前选中的分类索引
this.currentIndex = index;
},
},
};
</script>
<style>
.container {
display: flex;
flex-direction: row;
height: 100%;
}
.left {
width: 30%;
height: 100%;
background-color: #f2f2f2;
padding: 10px;
}
.left .active {
color: #007aff;
font-weight: bold;
}
.right {
flex: 1;
height: 100%;
padding: 10px;
}
.right image {
width: 100%;
height: 200px;
object-fit: cover;
}
</style>
```
在这个示例中,我们定义了一个 `categories` 数组作为左侧分类列表,以及一个 `products` 数组作为右侧商品列表。同时,我们使用了一个 `currentIndex` 变量来记录当前选中的分类索引。当用户点击左侧分类列表中的某个分类时,我们会更新 `currentIndex` 变量,然后根据当前选中的分类来过滤右侧商品列表中的商品。最后,我们使用了 `v-for` 指令来循环渲染左侧分类列表和右侧商品列表,并使用了 `class` 绑定来控制左侧选中的分类样式。