vue3:写一个自定义穿梭框(1)

最近项目有个需求,需要对穿梭框里面的数据进行框选。然而项目本身是基于ant-design-vue组件库的。antd的组件并不支持这个功能。

好在需求有相关实现的参考。那是一个jquery时代的老项目了。实现起来很nice,只需要使用最原始的select - option 表单标签就行了。因为浏览器本身支持select表单选项的框选多选等快捷操作。

于是事情变得简单了。

从最简单的例子开始写。

   <select multiple>
      <option value="1">选项1</option>
      <option value="2">选项2</option>
   </select>

给select设置multiple属性后,显示上就会变为列表。然而要用到穿梭框上,需要再美化一下。

接下来,我封装了一个组件。

 <template>
<select multiple ref="selectRef" @change="onChange">
 <option v-for="(item, key) in items" :key="key" :value="item.value" :style="optionStyle">
   <slot name="render" v-bind="item">
     {{ item.label }}
   </slot>
 </option>
</select>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
const emit = defineEmits(['change']);
const props = defineProps({
 itemStyle: {
   type: Object,
   default() {
     return {};
   },
 },
 items: {
   type: Array,
   default() {
     return [];
   },
 },
});
const optionStyle = computed(() => {
 return props.itemStyle || {};
});
const onChange = (val) => {
 const arr = [];
 const length = val.target.selectedOptions.length;
 for (let i = 0; i < length; i++) {
   // value 为字符串, _value是原始值
   arr.push(val.target.selectedOptions[i]._value);
 }
 emit('change', arr);
};
</script>

这是最简版的,选择列表从items参数传入,选择的变更通过change 事件提供出去。 随着开发的深入,还发现一些问题。当选择完数据移到另一侧列表的时候,虽然原来选择的数据移除了,但选择状态还呈现在列表中。这时就需要一个方法清除选择。

  const selectRef = ref();
  const resetSelected = () => {
    let arr = [...selectRef.value.selectedOptions];
    for (let i = 0; i < arr.length; i++) {
      arr[i].selected = false;
    }
  };
  defineExpose({
    resetSelected,
  });

列表组件写好了。构想一下最终要呈现的界面

先把template大致定下来

<template>
  <div :class="`${prefixCls}__container`">
    <div :class="`${prefixCls}__left ${prefixCls}__wrapper`">
      <div :class="`${prefixCls}__title-con`">
        <div :class="`${prefixCls}__title`">
          {{ titles[0] || '所有项目' }}
        </div>
        <div :class="`${prefixCls}__number`">
          ({{ leftData.selectedKeys.length > 0 ? `${leftData.selectedKeys.length}/` : ''
          }}{{ leftData.filterItems.length }})
        </div>
      </div>
      <div :class="`${prefixCls}__search`" v-if="showSearch">
        <a-input v-model:value="leftData.searchValue" allow-clear />
      </div>
      <OriginList
        v-if="mode === 'origin'"
        ref="leftoriginRef"
        :items="leftData.filterItems"
        @change="leftChange"
        :item-style="itemStyle"
        :style="listStyle"
      >
        <template #render="item" v-if="mode === 'origin'">
          <slot name="render" v-bind="item"></slot>
        </template>
      </OriginList>
    </div>
    <div :class="`${prefixCls}__operations`">
      <slot name="buttonBefore"></slot>
      <div :class="`${prefixCls}__button`" @click="moveToRight">
        <slot name="rightButton">
          <a-button type="default">
            <DoubleRightOutlined />
          </a-button>
        </slot>
      </div>
      <slot name="buttonCenter"></slot>
      <div :class="`${prefixCls}__button`" @click="moveToLeft">
        <slot name="leftButton">
          <a-button type="default">
            <DoubleLeftOutlined />
          </a-button>
        </slot>
      </div>
      <slot name="buttonAfter"></slot>
    </div>
    <div :class="`${prefixCls}__right ${prefixCls}__wrapper`">
      <div :class="`${prefixCls}__title-con`">
        <div :class="`${prefixCls}__title`">
          {{ titles[1] || '已选项目' }}
        </div>
        <div :class="`${prefixCls}__number`">
          ({{ rightData.selectedKeys.length > 0 ? `${rightData.selectedKeys.length}/` : ''
          }}{{ rightData.filterItems.length }})
        </div>
      </div>
      <div :class="`${prefixCls}__search`" v-if="showSearch">
        <a-input v-model:value="rightData.searchValue" allow-clear />
      </div>
      <OriginList
        v-if="mode === 'origin'"
        ref="rightoriginRef"
        :items="rightData.filterItems"
        @change="rightChange"
        :item-style="itemStyle"
        :style="listStyle"
      >
        <template #render="item" v-if="mode === 'origin'">
          <span :style="itemStyle">
            <slot name="render" v-bind="item"></slot>
          </span>
        </template>
      </OriginList>
    </div>
  </div>
</template>

可以看到,左右两侧都分别有头部,搜索框,列表。
这两个列表有很多方法和状态是相同的。这时vue3 的composition Api 的优势就发挥出来了。

写一个方法,包含这些状态:

import { reactive, computed, watch } from 'vue';
export function useList() {
  const data = reactive({
    filterItems: [],
    searchValue: '',
    selectedKeys: [],
    checkAll: false,
  });
  function selectedChange(val) {
    data.selectedKeys = val;
  }

  return {
    data,
    selectedChange,
  };
}

在穿梭框主体script上:

<script setup lang="ts" name="ExtTransfer">
  import { ref, computed, watch, watchEffect } from 'vue';
  import OriginList from './OriginList.vue';
  import { useList } from './hooks/useList';
  const props = defineProps({
    showSearch: {
      type: Boolean,
      default: true,
    },
    dataSource: {
      type: Array,
      default() {
        return [];
      },
    },
    targetKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    filterOption: {
      type: Function,
      default: filterOption,
    },
    listStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    titles: {
      type: Array,
      default() {
        return [];
      },
    },
    itemStyle: {
      type: Object,
      default() {
        return {};
      },
    },
  });
  const emit = defineEmits(['change']);
  // 左侧框
  const leftoriginRef = ref();
  const { data: leftData, indeterminate: leftIndete, selectedChange: leftChange } = useList();
  // 右侧框
  const rightoriginRef = ref();
  const { data: rightData, indeterminate: rightIndete, selectedChange: rightChange } = useList();

  const targetKeys = ref([]);
  const targetItems = computed(() => {
    return props.dataSource.filter((item) => {
      return targetKeys.value.includes(item.value);
    });
  });
  watch(
    () => props.targetKeys,
    (val) => {
      targetKeys.value = val;
    },
    {
      immediate: true,
    },
  );
  watchEffect(() => {
    const leftSearch = leftData.searchValue;
    const rightSearch = rightData.searchValue;
    if (leftSearch.trim() === '') {
      leftData.filterItems = props.dataSource.filter((item) => {
        return !targetKeys.value.includes(item.value);
      });
    } else {
      leftData.filterItems = props.dataSource.filter((option) => {
        return !targetKeys.value.includes(option.value) && props.filterOption(leftSearch, option);
      });
    }
    if (rightSearch.trim() === '') {
      rightData.filterItems = [...targetItems.value];
    } else {
      rightData.filterItems = targetItems.value.filter((option) => {
        return props.filterOption(rightSearch, option);
      });
    }
  });
  function moveToRight() {
    leftoriginRef.value?.resetSelected();
    targetKeys.value = [...targetKeys.value, ...leftData.selectedKeys];
    leftData.selectedKeys = [];
    emit('change', targetKeys.value);
  }
  function moveToLeft() {
    const arr = [];
    const length = targetKeys.value.length;
    for (let i = 0; i < length; i++) {
      const item = targetKeys.value[i];
      if (!rightData.selectedKeys.includes(item)) {
        arr.push(item);
      }
    }
    targetKeys.value = arr;
    rightData.selectedKeys = [];
    rightoriginRef.value?.resetSelected();
    emit('change', targetKeys.value);
  }
  function resetSearch() {
    leftData.searchValue = '';
    rightData.searchValue = '';
  }
  defineExpose({
    resetSearch,
  });
</script>

穿梭框在参数设计上,为了照顾使用习惯,尽量跟随ant design vue 穿梭框的参数,为了使代码简洁。使用watchEffet方法进行监听。这样,不管在搜索或者数据源变动时,列表都能刷新。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,387评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,845评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,091评论 0 246
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,308评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,662评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,795评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,008评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,743评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,466评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,687评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,181评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,531评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,177评论 3 239
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,126评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,862评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,734评论 2 274

推荐阅读更多精彩内容