zoukankan      html  css  js  c++  java
  • 子、父组件的数据传递(实战篇)

    做一个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) 
           }
        }    
  • 相关阅读:
    Extjs4.0中清空filefield已选文件
    .net操作读取word中的图像并保存
    WebForm_PostBackOptions未定义 错误排查
    数据库关键字
    VS2008生成WebSite和WebApplication的区别(转载)
    安装天乙论坛(SSH架构的开源项目)时遇到的问题
    Hibernate与Oracle char类型的列之间的兼容问题
    关于spring3使用AOP编程时需要引入哪些jar包的问题
    让IE支持HTML5的Canvas
    IIS + TOMCAT 注意事项
  • 原文地址:https://www.cnblogs.com/lanSeGeDiao/p/8947909.html
Copyright © 2011-2022 走看看