vue中$emit传递多个参数 需要父组件传参区分类型时

1.$emit传递一个参数的情况

//child组件,在子组件中触发事件
this.$emit('handleFather', param)
//father组件,在父组件中引用子组件
<child @handleFather="handleFather"></child>
//或者
//<child @handleFather="handleFather($event)"></child>
 
<script>
    export default {
      components: {
       child,
      }
      methods: {
        handleFather(param) {
            console.log(param)
        }
      }
    },
</script>

        补充:传递一个参数,也可以是对象类型 {}

2.$emit传递多个参数的情况

//child组件,在子组件中触发事件并传多个参数
this.$emit('handleFather', param1, param2,)
//father组件,在父组件中引用子组件
<child @handleFather="handleFather(arguments)"></child>
 
<script>
    export default {
      components: {
       child,
      }
      methods: {
        handleFather(param) {
            console.log(param[0]) //获取param1的值
            console.log(param[1]) //获取param2的值
 
        }
      }
    },
</script>

3.当需要父组件本身传参时

//child组件,在子组件中触发事件
this.$emit('handleFather', param)
//father组件,在父组件中引用子组件
<child @handleFather="handleFather($event, fatherParam)"></child>
 
<script>
    export default {
      components: {
       child,
      }
      methods: {
        handleFather(childParam, fatherParam) {
            console.log(childParam)
            console.log(fatherParam)
        }
      }
    },
</script>
//child组件,在子组件中触发事件并传多个参数
this.$emit('handleFather', param1, param2,)
//father组件,在父组件中引用子组件
<child @handleFather="handleFather(arguments, fatherParam)"></child>
 
<script>
    export default {
      components: {
       child,
      }
      methods: {
        handleFather(childParam, fatherParam) {
            console.log(childParam) //获取arguments数组参数
            console.log(fatherParam) //获取fatherParam
 
        }
      }
    },
</script>

补充实践(很重要):

子组件vue文件:

<template>
 <div>
    <el-select v-model="selectType" @change="handleSwichType">
        <el-option label="一级" value="01">
        </el-option>
        <el-option label="二级" value="02">
        </el-option>
    </el-select>
...
 </div>
</template>
<script>
export default {
    data(){
      return {
        selectType: '',
   }
  },
methods: {
    handleSwitchType(){
        this.$emit('handleSwitchType',this.selectType)
    }
}
</script>
  

父组件vue文件:

<Child @handleSwitchType="handleSwitchType($event,'01')">
  //默认插槽位置内容
  <div>设备计划模块:</div>
        <div>计划一:。。。</div>
        <div>计划二:。。。</div>
</Child>

<Child @handleSwitchType="handleSwitchType($event,'02')">
  //默认插槽位置内容
  <div>地市分布统计模块:</div>
        <div>济南:。。。</div>
        <div>青岛:。。。</div>
</Child>

<script>
methods: {
    handleSwitchType(chidParam,faterParam){
        console.log(childParam,faterParam)
        //此处可以根据父组件传的参数faterParam来加载不同模块的数据
        if(faterParam == '01'){
            init_1()  //加载设备计划模块的接口数据
        }else {
            init_2()  //加载地市分布模块的接口数据
        }
    }
}
</script>

此应用主要用来区分子组件触发的handleSwitchType,是父组件的哪个handleSwitchType。

猜你喜欢

转载自blog.csdn.net/weixin_51747462/article/details/128853002