返回

扩展Vue组件:添加动画效果的树状递归展开组件

前端

前段时间要做一个树状递归的展开组件,原来都是用的第三方框架直接用,突然要用一个自定义能力比较强的,就想着看看有没有写的差不多的自己改一下得了,结果用某度搜了一下,清一色复制粘贴的文章,而且也写的极其简单,关键是自己再改还是要费不少精力。

所以基于此,自己在网上找到了一个成品,自己简单调整了一下,可以根据传入不同的参数显示不同的样式,顺便加上了一些动画效果,因为组件自己有动画效果,所以就用css3的transform来实现动画,有兴趣的可以研究一下,代码如下:

export default Vue.component('tree-view', {
  props: {
    data: {
      type: Object,
      required: true
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    childrenKey: {
      type: String,
      default: 'children'
    },
    openDefault: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isOpen: false
    }
  },
  mounted() {
    this.isOpen = this.openDefault
  },
  methods: {
    toggle() {
      this.isOpen = !this.isOpen
    }
  },
  render(h) {
    const { labelKey, childrenKey } = this.$props

    let children = null
    if (this.isOpen && this.data[childrenKey] && this.data[childrenKey].length) {
      children = h('ul', {
        staticClass: 'tree-view-children'
      }, this.data[childrenKey].map(item => h('tree-view', {
        props: {
          data: item,
          labelKey,
          childrenKey,
          openDefault: this.openDefault
        }
      })))
    }

    return h('li', {
      staticClass: 'tree-view-item',
      on: {
        click: this.toggle
      }
    }, [
      h('span', this.data[labelKey]),
      children
    ])
  }
})
<style>
.tree-view {
  list-style: none;
  padding: 0;
  margin: 0;
}

.tree-view-item {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  cursor: pointer;
}

.tree-view-item:hover {
  background-color: #f5f5f5;
}

.tree-view-children {
  display: none;
}

.tree-view-item-open .tree-view-children {
  display: block;
}

.tree-view-item-open > span {
  transform: rotate(90deg);
}
</style>

通过以上代码,我们便能实现一个带有动画效果的树状递归展开组件。该组件具有许多优势,例如:

  • 灵活的配置:可以根据需要自定义标签和子元素的键,并控制组件的默认打开状态。
  • 动画效果:使用CSS3的transform属性实现平滑的展开和折叠动画,增强用户体验。
  • 递归结构:组件可以递归渲染数据,轻松构建复杂的树状结构。

希望这篇文章对您有所帮助!