Bootstrap

【Vue实用组件】排序布局

排序布局

  • 简述:使用此组件可以灵活改变插入元素中的顺序和显隐状态。
  • 使用场景:需要根据动态条件渲染的复杂组件场景。例如表单区域中按条件渲染指定的表单交互项组件。

组件源码 (Vue2)

<script>
/**
 *  排序布局
 *  @param  {String}          tag   包囊元素标签
 *  @param  {Array|Function}  sort  元素插入顺序 ( Array[String|VNode] | Function )
 */
export default {
  name: 'SortLayout',
  functional: true,
  inheritAttrs: false,
  props: {
    tag: { type: String, default: 'span' },
    sort: { type: [Array, Function], default: void 0 }
  },
  render(h, { data, props: { tag, sort }, slots }) {
    const children = []
    const slotList = slots && slots().default || []
    if (typeof sort == 'function') sort = sort(slotList)
    if (Array.isArray(sort)) {
      for (let item of sort) {
        if (item == null) continue
        if (typeof item == 'string' || typeof item == 'number') {
          item = slotList.find(v => v.key === item)
          item && children.push(item)
        } else if (typeof item == 'object' && slotList.includes(item)) {
          children.push(item)
        }
      }
    }
    return h(tag, data, children)
  }
}
</script>

使用示例

<template>
  <div>
    <SortLayout tag="div" :sort="sortKeys" class="demo1">
      <div key="1">A</div>
      <div key="2">B</div>
      <div key="3">C</div>
      <div key="4">D</div>
      <div :key="4">E</div>
      <div :key="5">F</div>
      <div :key="6">G</div>
      <div>Default</div>
    </SortLayout>
    <SortLayout tag="ul" :sort="sortMethod" class="demo2">
      <li key="a">1</li>
      <li key="b">2</li>
      <li key="c">3</li>
      <li key="d">4</li>
      <li key="e">5</li>
      <li key="f">6</li>
    </SortLayout>
  </div>
</template>

<script>
import SortLayout from '@/components/SortLayout'

export default {
  components: { SortLayout },
  data() {
    return {
      sortKeys: []
    }
  },
  mounted() {
    const sortKeys = [
      ['3', '2', 5, 4],
      ['1', '6', '4', 6, 4],
      [6, 5, 4, 3, 2, 1],
      ['1', '2', '3', '4', 4, 5, 6]
    ]
    setInterval(() => {
      this.sortKeys = sortKeys[Math.floor(Math.random() * sortKeys.length)]
    }, 3000)
  },
  methods: {
  	sortMethod(slots) {
  	  return slots.sort(() => Math.floor(Math.random() * 3) - 1)
  	}
  }
}
</script>
;