vue3:寫一個自定義穿梭框(1)

最近項目有個需求土铺,需要對穿梭框里面的數(shù)據(jù)進(jìn)行框選。然而項目本身是基于ant-design-vue組件庫的。antd的組件并不支持這個功能理郑。

好在需求有相關(guān)實現(xiàn)的參考。那是一個jquery時代的老項目了咨油。實現(xiàn)起來很nice您炉,只需要使用最原始的select - option 表單標(biāo)簽就行了。因為瀏覽器本身支持select表單選項的框選多選等快捷操作臼勉。

于是事情變得簡單了邻吭。

從最簡單的例子開始寫。

   <select multiple>
      <option value="1">選項1</option>
      <option value="2">選項2</option>
   </select>

給select設(shè)置multiple屬性后宴霸,顯示上就會變?yōu)榱斜泶亚纭H欢玫酱┧罂蛏希枰倜阑幌隆?/p>

接下來瓢谢,我封裝了一個組件畸写。

 <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參數(shù)傳入枯芬,選擇的變更通過change 事件提供出去。 隨著開發(fā)的深入采郎,還發(fā)現(xiàn)一些問題千所。當(dāng)選擇完數(shù)據(jù)移到另一側(cè)列表的時候,雖然原來選擇的數(shù)據(jù)移除了蒜埋,但選擇狀態(tài)還呈現(xiàn)在列表中淫痰。這時就需要一個方法清除選擇。

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

列表組件寫好了整份。構(gòu)想一下最終要呈現(xiàn)的界面

先把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>

可以看到待错,左右兩側(cè)都分別有頭部籽孙,搜索框,列表火俄。
這兩個列表有很多方法和狀態(tài)是相同的犯建。這時vue3 的composition Api 的優(yōu)勢就發(fā)揮出來了。

寫一個方法瓜客,包含這些狀態(tài):

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']);
  // 左側(cè)框
  const leftoriginRef = ref();
  const { data: leftData, indeterminate: leftIndete, selectedChange: leftChange } = useList();
  // 右側(cè)框
  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>

穿梭框在參數(shù)設(shè)計上适瓦,為了照顧使用習(xí)慣,盡量跟隨ant design vue 穿梭框的參數(shù)忆家,為了使代碼簡潔犹菇。使用watchEffet方法進(jìn)行監(jiān)聽。這樣芽卿,不管在搜索或者數(shù)據(jù)源變動時揭芍,列表都能刷新。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末卸例,一起剝皮案震驚了整個濱河市称杨,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌筷转,老刑警劉巖姑原,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異呜舒,居然都是意外死亡锭汛,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門袭蝗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來唤殴,“玉大人,你說我怎么就攤上這事到腥《涫牛” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵乡范,是天一觀的道長配名。 經(jīng)常有香客問我,道長晋辆,這世上最難降的妖魔是什么渠脉? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮瓶佳,結(jié)果婚禮上连舍,老公的妹妹穿的比我還像新娘。我一直安慰自己涩哟,他們只是感情好索赏,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著贴彼,像睡著了一般潜腻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上器仗,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天融涣,我揣著相機與錄音,去河邊找鬼精钮。 笑死威鹿,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的轨香。 我是一名探鬼主播忽你,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼臂容!你這毒婦竟也來了科雳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤脓杉,失蹤者是張志新(化名)和其女友劉穎糟秘,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體球散,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡尿赚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蕉堰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凌净。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖嘁灯,靈堂內(nèi)的尸體忽然破棺而出泻蚊,到底是詐尸還是另有隱情,我是刑警寧澤丑婿,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布性雄,位于F島的核電站,受9級特大地震影響羹奉,放射性物質(zhì)發(fā)生泄漏秒旋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一诀拭、第九天 我趴在偏房一處隱蔽的房頂上張望迁筛。 院中可真熱鬧,春花似錦耕挨、人聲如沸细卧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贪庙。三九已至蜘犁,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間止邮,已是汗流浹背这橙。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留导披,地道東北人屈扎。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像撩匕,于是被迫代替她去往敵國和親鹰晨。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容