Data transfer of child and parent components (practical chapter)

Make a selection component for actual combat. The effect picture is as follows

The following is the simulated data data

   data () {
      return {
        buyTypes: [
          {  label: 'java', value: 0 },
          {  label: 'vue',  value: 1 },
          {  label: 'node', value: 2 }
        ]
    }
  }

The following is the pseudo code of the subcomponent

<!-- Idea: Set a nowIndex to determine which number is clicked each time, and then get the number of data so that it can be returned to the parent component.
  Pseudocode for selections component -->
<template>
  <div class="selection-component">
    <div class="selection-show" @click="toggleDrop" > <!--Listen to click events to show or hide the drop-down content-->
      <span>{{selections[nowIndex].label}}</span> <!--Show selections-->
      <div class="arrow"></div>
    </div>
    <div class="selection-list" v- if ="isDrop"> <!--Show hidden drop-down box-->
      <ul>
        <!--Cycle returns the data of the child component from the parent component and displays it in a loop to listen for click events in li-->
        <li v-for="(item, index) in selections" @click="chooseSelection(index)">{{ item.label }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      selections: {
        type: Array, // Limited sub-components can only accept array type 
        default : [{ // Default all data 
          label: 'all' ,
          value: 0
        }]
      }
    },
    data () {
      return {
        isDrop:false,
        nowIndex:0
      }
    },
    methods: {
      toggleDrop () {
        this.isDrop = !this.isDrop
      },
      chooseSelection (index) {
        this .nowIndex = index
         this .isDrop = false 
        this .$emit('on-change', this .selections[ this .nowIndex]) // like the parent component returns the clicked data 
      }
    }
  }
</script>

The following is the key pseudo code of the parent component

// The parent component calls the method to listen to the custom event to get the parameters returned by the child component
  <v-selection :selections="buyTypes" @on-change="getProIndex" ></v-selection>

 methods: {
      getProIndex(value){
         console.log(value)
       }
    }    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324853530&siteId=291194637