Component ideas and functions

Refer to Ant Design for general UI,

Primary interaction logic

The usage method to be implemented

<cascader dataSource="data" onChange="onChange">
  <button>toggle</button>  <! -- Optional slot trigger --> 
</cascader>
Copy the code

Determine the input data format

const source = [{
        name: 'spring'.children: [{name: 'flowers'},
          {name: 'warm'},
          {name: 'Shining light'}]}, {name: 'summer'.children: [{name: 'hot'},
          {name: 'cool'}},]]Copy the code

Think about how to render data

The key problem with rendering data is that you can’t do V-for rendering for each layer without knowing exactly how many layers the data is in.

Recursively render

The question arises again, how do you use yourself in a component?

The cascaderItem.vue component can be created as follows:

const cascaderItem = {
  name: 'cascaderItem'.components: {
    cascaderItem: cascaderItem
  },
  props: {
    sourceItem: {
      type: Object}}}export default cascaderItem
Copy the code

Can be used in template

<div>
    {{sourceItem.name}}
    <cascader-item
      v-for="item in sourceItem.children"
      v-if="sourceItem.children"
      :source-item="item"
    ></cascader-item>
  </div>
Copy the code

In fact, it can be written just like a normal component. Vue supports the use of tags that are the same as name, and the default is to use itself

export default {
 name: 'cascaderItem'.props: {
   sourceItem: {
     type: Object}}}Copy the code

At this point, we can introduce the item component in cascader.vue and use it to render the data, first displaying the data roughly:

Render pop-ups

cascaderItem.vue

<div class="cascaderItem">
    <div class="left">
      <div class="label" v-for="item in items" @click="leftSelected = item">
        {{item.name}}
      </div>
    </div>
    <div class="right" v-if="rightItems">
      <cascader-item :items="rightItems" />
    </div>
  </div>
Copy the code

There are only left and right containers, recursive rendering

export default {
  name: 'cascaderItem'.props: {
    items: {
      type: Array}},data() {
    return {
      leftSelected: null}},computed: {
    rightItems() {
      if(this.leftSelected && this.leftSelected.children) {
        return this.leftSelected.children
      } else {
        return null}}}}Copy the code

Just pass in the popover section of cascader.vue

<template>
  <div class="cascader">
    <div class="trigger" @click="popoverVisible=! popoverVisible"></div>
    <div class="popover" v-if="popoverVisible">
      <cascader-item :items="source" />
    </div>
  </div>
</template>
Copy the code

The first rendering of the pop-up layer is done,