Vue - component recursion

component recursion

When rendering a directory, because there may be nested data and the level of the component is unknown, component recursion can be used to solve the problem.

important point:

1. It must be provided when using recursion name, that is, through the component's namerecursion itself .

2. Pay attention to component event delivery.

Example:

Subassembly

<template>
  <ul>
    <li v-for="(item, index) in list" :key="index">
      <span @click="handleClick(item)">{
   
   { item.name }}</span>
      <RecursionList v-if="item.children?.length" :list="item.children" @clickItem="handleClick"/>
    </li>
  </ul>
</template>

<script>
export default {
      
      
  name: 'RecursionList',
  props: {
      
      
    list: {
      
      
      type: Array,
      default: () => []
    }
  },
  methods: {
      
      
    handleClick(item) {
      
      
      this.$emit('clickItem', item)
    }
  }
}
</script>

parent component

<template>
  <RecursionList :list="list" @clickItem="getItem" />
</template>

<script>
import RecursionList from './components/RecursionList.vue'
export default {
      
      
  components: {
      
      
    RecursionList
  },
  data() {
      
      
    return {
      
      
      list: [
        {
      
       name: 'a' }, 
        {
      
       name: 'b' }, 
        {
      
       name: 'c', 
          children: [{
      
       name: 'ca' }, {
      
       name: 'cb' }, {
      
       name: 'cc', children: [] }] 
        }
      ]
    }
  },
  methods: {
      
      
    getItem(item) {
      
      
      console.log(item)
    }
  }
}
</script>

that's all.

Supongo que te gusta

Origin blog.csdn.net/qq_40147756/article/details/133365695
Recomendado
Clasificación