要实现选中只拿子级的值,可以使用treeselect组件的@select事件,然后在事件处理程序中获取子级的值。

首先,需要在组件中引入vue-treeselect组件,并注册treeselect组件:

<template>
  <div>
    <treeselect
      :options="options"
      multiple
      @select="handleSelect"
    ></treeselect>
  </div>
</template>

<script>
import 'vue-treeselect/dist/vue-treeselect.css'
import Treeselect from 'vue-treeselect'

export default {
  components: {
    Treeselect
  },
  data() {
    return {
      options: [
        { id: 1, label: 'Option 1', children: [
          { id: 11, label: 'Option 1-1' },
          { id: 12, label: 'Option 1-2' }
        ]},
        { id: 2, label: 'Option 2', children: [
          { id: 21, label: 'Option 2-1' },
          { id: 22, label: 'Option 2-2' }
        ]}
      ]
    }
  },
  methods: {
    handleSelect(selectedNodes) {
      const selectedValues = selectedNodes.map(node => node.id)
      console.log(selectedValues)
      // 只拿子级的值
      const selectedChildValues = selectedNodes.reduce((values, node) => {
        if (node.children) {
          values.push(...node.children.map(child => child.id))
        }
        return values
      }, [])
      console.log(selectedChildValues)
    }
  }
}
</script>

在这个例子中,options数组包含了一个父级选项和子级选项。当选择一个选项时,会触发@select事件,并调用handleSelect方法来处理选中的节点。

handleSelect方法中,首先获取所有选中节点的值,然后使用reduce方法遍历选中节点数组,如果节点有子级,就将子级的值添加到selectedChildValues数组中。

这样,selectedChildValues数组中就只包含了选中节点的子级值。你可以根据自己的需求进一步处理这些值

vue-treeselect 选中只拿子级的值

原文地址: http://www.cveoy.top/t/topic/irn8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录