实现京东多条件筛选功能可以使用Vue3和TypeScript。具体实现步骤如下:
1. 定义筛选项数据结构
首先,需要定义一个筛选项的数据结构,例如:
```typescript
interface FilterOption {
label: string;
value: string;
}
```
2. 定义筛选条件数据结构
接下来,需要定义一个筛选条件的数据结构,例如:
```typescript
interface FilterCondition {
label: string;
options: FilterOption[];
selectedOption?: FilterOption;
}
```
其中,`label` 表示筛选条件的名称,`options` 表示该条件下的所有筛选项,`selectedOption` 表示当前选中的筛选项。
3. 定义筛选条件组件
根据上面定义的数据结构,可以定义一个筛选条件的组件,例如:
```vue
<template>
<div>
<h3>{{ condition.label }}</h3>
<ul>
<li v-for="option in condition.options" :key="option.value">
<input
type="radio"
:id="option.value"
:value="option.value"
v-model="condition.selectedOption"
/>
<label :for="option.value">{{ option.label }}</label>
</li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { FilterCondition } from './types';
export default defineComponent({
props: {
condition: {
type: Object as () => FilterCondition,
required: true,
},
},
});
</script>
```
在该组件中,通过 `v-for` 循环渲染所有筛选项,并通过 `v-model` 实现单选框的选中状态绑定。
4. 定义筛选条件组合组件
接下来,需要定义一个筛选条件组合的组件,例如:
```vue
<template>
<div>
<h2>筛选条件</h2>
<div v-for="(condition, index) in conditions" :key="index">
<FilterCondition :condition="condition" />
</div>
<button @click="reset">重置</button>
<button @click="submit">确定</button>
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue';
import { FilterCondition } from './types';
export default defineComponent({
props: {
conditions: {
type: Array as () => FilterCondition[],
required: true,
},
},
setup(props, { emit }) {
const reset = () => {
props.conditions.forEach((condition) => {
condition.selectedOption = undefined;
});
};
const submit = () => {
const selectedConditions = props.conditions.filter(
(condition) => condition.selectedOption
);
emit('submit', selectedConditions);
};
const hasSelectedCondition = computed(() =>
props.conditions.some((condition) => condition.selectedOption)
);
return {
reset,
submit,
hasSelectedCondition,
};
},
});
</script>
```
在该组件中,通过 `v-for` 循环渲染所有筛选条件,并通过 `reset` 和 `submit` 方法实现重置和确定操作。通过 `emit` 发送 `submit` 事件,将选中的筛选条件传递给父组件。
5. 在父组件中使用筛选条件组合组件
最后,在父组件中使用筛选条件组合组件,并监听 `submit` 事件,例如:
```vue
<template>
<div>
<FilterConditions :conditions="conditions" @submit="handleFilter" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { FilterCondition } from './types';
export default defineComponent({
components: {
FilterConditions,
},
data() {
return {
conditions: [
{
label: '品牌',
options: [
{ label: '华为', value: 'huawei' },
{ label: '小米', value: 'xiaomi' },
{ label: '苹果', value: 'apple' },
],
},
{
label: '价格',
options: [
{ label: '500以下', value: '0-500' },
{ label: '500-1000', value: '500-1000' },
{ label: '1000以上', value: '1000-' },
],
},
] as FilterCondition[],
};
},
methods: {
handleFilter(selectedConditions: FilterCondition[]) {
// 处理筛选结果
},
},
});
</script>
```
在父组件中,通过 `conditions` 属性传递筛选条件数据,监听 `submit` 事件,处理筛选结果即可。
以上就是实现京东多条件筛选功能的基本步骤,具体实现还需要根据实际需求进行调整。