快捷搜索: 王者荣耀 脱发

Vue3 defineProp传参以及defineEmits事件传递详细解释

defineProp父子组件传参

vue3中引用另一个组件非常简单,不再需要设置各个组件的name,直接import导入即可! 下方代码,父组件为PropSuper.vue 子组件为PropBase.vue

<template>
    <prop-base-vue></prop-base-vue>
</template>

<script setup lang="ts">
// 导入取名随意!
import PropBaseVue from ./PropBase.vue;
</script>

传参实例 和vue2不同,使用defineProps替代原来的props传参;

  1. 代码中上半部分为父组件,下半部分为子组件
  2. :array=“arr” 当传给子组件的参数为非字符串类型,就需要使用v-bind绑定,array为子组件内数据名称,arr为父组件内数据名称
  3. title=“base” 因为传入的是string类型,不需要v-bind绑定
  4. 子组件先使用type定义存放接收数据的变量类型,然后作为类型传入defineProps后大功告成
  5. 直接使用插值语法调用type内定义的变量即可取出数据!!!
<!-- PropSuper.vue代码清单 -->
<template>
    <prop-base-vue :array="arr" title="base"></prop-base-vue>
</template>

<script setup lang="ts">
import PropBaseVue from ./PropBase.vue;
import {
            
      reactive } from vue;

const arr = reactive([1,2,3])
</script>


<!-- PropBase.vue代码清单 -->
<template>
    <div>
        {
         
  {title}}-{
         
  {array}}
    </div>
</template>

<script setup lang="ts">
import {
            
      type } from os;
import {
            
      reactive } from vue;

type props = {
            
         // 设置类型
    title:string,
    array:number[]
}
defineProps<props>()  // 将类型直接传入即可
</script>

defineEmits事件传递

此方法为子给父传递信息

  1. @tap=“getName” tap为子组件内发送数据的方法,getName为父组件内接收数据的方法
  2. const getName 父组件内定义一个方法来接收子组件传入的数据,因为使用ts,所以要显式指定形参类型
  3. <button @click=“tap”> 子组件设置一按钮点击事件连接到tap方法
  4. defineEmits 接收一数组,数组内填发送数据的方法名称,且defineEmits需被赋予到一个变量上去
  5. emit(‘tap’, list) 触发数据发送事件,参一为方法名,参二及以后的参数为传入的实参!!!
<!-- EmitSuper.vue -->
<template>
    <emit-base-vue @tap="getName"></emit-base-vue>
</template>

<script setup lang="ts">
import EmitBaseVue from ./EmitBase.vue;
const getName = (list: number[]) => {
            
     
    console.log(list);
}
</script>


<!-- EmitBase.vue -->
<template>
    <div>
        <button @click="tap"></button>
    </div>
</template>

<script setup lang="ts">
import {
            
      reactive } from vue;
const list = reactive([1, 2, 3])

const emit = defineEmits([tap])
const tap = () => {
            
     
    emit(tap, list)
}
</script>

经验分享 程序员 微信小程序 职场和发展