In vue, $emit passes multiple parameters, the use of "arguments" and "$event"

foreword

$emitWhen passing data from child components to parent components, there are mainly the following three types of situations

1. Only subcomponents pass values ​​(single, multiple)

Writing method 1: (free style)

// child组件,在子组件中触发事件
this.$emit('handleFather', '子参数1','子参数2','子参数3')
// father组件,在父组件中引用子组件
<child @handleFather="handleFather"></child>
<script>
export default {
    
    
   components: {
    
    
    child,
   }
   methods: {
    
    
     handleFather(param1,param2,param3) {
    
    
         console.log(param) // 
     }
   }
 }
 </script>

Parse:

  1. Only subcomponents pass values;
  2. Note that @ reference function does not need to add "brackets";
  3. The value passed by the child component corresponds to the parameter of the parent component method one by one.

Writing method 2: (arguments writing method)

// 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>

Parse:

  1. Only subcomponents pass values;
  2. Note that the @reference function adds the "arguments" value;
  3. Print out the array form of the value passed by the subcomponent.

2. The child component passes the value, and the parent component also passes the value

Writing method one:

// child组件,在子组件中触发事件
this.$emit('handleFather', '子参数对象')
//father组件,在父组件中引用子组件
<child @handleFather="handleFather($event, fatherParam)"></child>
 
<script>
 export default {
    
    
   components: {
    
    
    child,
   }
   methods: {
    
    
     handleFather(childObj, fatherParam) {
    
    
         console.log(childObj) // 打印子组件参数(对象)
         console.log(fatherParam) // 父组件参数
     }
   }
 }
</script>

Writing method two:

// 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>

Summarize:

  • Only subcomponents pass parameters, @ call method does not use "brackets"
  • Special use " arguments" and " $event",
  • argumentsGet an array of subparameters
  • $eventGet a custom object that satisfies passing multiple parameters

Guess you like

Origin blog.csdn.net/weixin_35773751/article/details/128815238