子、父组件的数据传递(实战篇)

做一个selection 组件进行实战。效果图片如下

以下是模拟的data 数据

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

以下为子组件伪代码

<!-- 思想:设置一个nowIndex 来判断每次点击的是第几个,然后拿到第几个的数据这样就可以回传给父组件了。
  selections 组件的伪代码-->
<template>
  <div class="selection-component">
    <div class="selection-show"  @click="toggleDrop" >  <!--监听点击事件显示或者隐藏下拉内容-->
      <span>{{selections[nowIndex].label}}</span> <!--显示选择的内容-->
      <div class="arrow"></div>
    </div>
    <div class="selection-list" v-if="isDrop"> <!--显示隐藏下拉框-->
      <ul>
        <!--循环从父组件传回子组件的数据并循环显示在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, //限制子组件只能接受array 类型
        default: [{ //默认一个所有的数据
          label: '所有',
          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]) //像父组件回传点击的数据
      }
    }
  }
</script>

以下为父组件的关键伪代码

//父组件 调用方法监听自定义事件获取子组件回传的参数
  <v-selection :selections="buyTypes" @on-change="getProIndex" ></v-selection>

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

猜你喜欢

转载自www.cnblogs.com/lanSeGeDiao/p/8947909.html
今日推荐