setHook

2020-04-04  本文已影响0人  copyLeft

利用 setHook 实现简单的 tag 选择

name-tag.gif
<template>
  <div class="home">

    <div>
      <Card style='margin: 20% auto; width: 600px' title='Name Tag'>
        
        <div slot="extra" style="display: flex; align-items: center">
          <Button @click='reset' > reset </Button>
        </div>

        <div style='margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee'>
          <Tag v-for='item of set' :key='item.name' closable @on-close="remove(item)" >  {{ item.name }} - {{ item.age }} </Tag>
        </div>

        <div> 
          <template  v-for='item of users'>
            <Button 
            style='margin-right: 8px' 
            icon="ios-add" 
            type="dashed" 
            size="small" 
            @click="add(item)" 
            v-if='!set.has(item)' 
            :key='item.name'> 
              {{ item.name }}
            </Button>
          </template>
        </div>

      </Card>
    </div>
    
  </div>
</template>

<script>
import setHook from '@/hooks/setHook'


export default {

  setup(){

    const users = [
      
      {
        name: 'Coco',
        age: 24
      },
      {
        name: 'Jeck',
        age: 25
      },
      {
        name: 'Rogen'
      }

    ]

    const [ set, utils ] = setHook([ { name: 'copy', age: 34 } ])


    return {
      users,
      set,
      ...utils
    }

  }

}
</script>

hook 实现

import { ref } from '@vue/composition-api'


/**
 * Set hooks
 * @param { Array } initVal 初始数据
 * @summary 对Set类型做的hook封装,利用Set的幂等性
 * @exports 
 * const [ set, utils ] = setHook([ 1, 2 ])
 * 
 * 添加
 * set.add(3) ==> [1, 2, 3]
 * set.add(2) ==> [1, 2, 3]
 * 
 * 移除
 * set.remove(1) ==> [2, 3]
 * 
 * 重置
 * set.reset()  ==> [1, 2]
 * 
 * 
 * 其他Set方法
 * 
 * 校验
 * set.value.has(1) ==> true
 * 
 * 遍历
 * const newList = [...set.value].map(num => num + 1)  ==> [ 2, 3 ]
 * 
 */
export default function setHook(initVal=[]){

    const initSet = ref(new Set(initVal))
    const set = ref(new Set(initVal))
    
    const add = key => set.value = new Set([...[...set.value], key])
    const remove = key => set.value = new Set([...set.value].filter(i => i !== key))
    const reset = () => set.value = new Set([...initSet.value])
    const setInit = initVal => initSet.value = new Set(initVal)

    return [ set, {  add, remove, reset, setInit } ]
}
上一篇下一篇

猜你喜欢

热点阅读