美文网首页技术贴
vue3.0 父子传值

vue3.0 父子传值

作者: zhudying | 来源:发表于2023-09-07 16:59 被阅读0次
    props 父传子
    1. js - defineComponent
    import { defineComponent } from 'vue'
    export default defineComponent({
      props: {
          foo: String,
          bar: {
            type: Number,
            default: () => 1
          }  
      }
    })
    
    1. ts - defineComponent
    import { defineComponent } from 'vue'
    export default defineComponent({
      props: {
        foo: String,
        bar: { 
          type: String, 
          required: true 
        },
      }
    })
    // 复杂类型
    import { defineComponent } from 'vue'
    import type { PropType } from 'vue'
    interface Foo{
      name: string,
      age: number
    }
    
    export default defineComponent({
      props: {
        foo: {
          type:  Object as PropType<Foo>,
          default: () => {}
        },
        callback: Function as PropType<(id: string) => void>
      }
    })
    
    1. js - <script setup></script>
    <script setup>
      const props = defineProps({
          foo: String,
          bar: {
            type: Number,
            default: () => 1
          }
      })
    </script>
    
    1. ts - <script setup lang='ts'></script>
    <script setup lang='ts'>
       interface Props {
          foo: string,
          bar?: number
       }
       const props = defineProps<Props>()
    </script>
    // 解构默认值
    <script setup lang='ts'>
       interface Props {
          foo: string,
          bar?: number
       }
       const props = withDefaults(defineProps<Props>(), {
          foo: 'abc',
          bar: 12
       })
    </script>
    
    emit 子传父
    1. js - defineComponent
    export default defineComponent ({
      emits: ['change']
      setup(props, { emit }){
        emit('change') 
      }
    })
    
    1. js - <script setup></script>
    <script setup>
    const emit = defineEmits(['change'])
    emit('change)
    </script>
    
    1. ts - <script setup lang='ts'></script>
    const emit = defineEmits<
      change: [id: number]
    >()
    // 或者
    const emit = defineEmits<{
      (e: 'change', id: number): void
    }>()
    </script>
    
    ref 父组件获取子组件数据
    1. 子组件向外暴露
    const a = 2
    const b = () => {}
    defineExpose({
        a,
        b
    })
    
    1. 父组件通过 ref 获取
    <template>
      <child ref="childRef"></child>
    </template>
    
    <script setup>
      import { ref } from 'vue'
      const childRef = ref()
      childRef.value.a // 获取
    </script>
    

    相关文章

      网友评论

        本文标题:vue3.0 父子传值

        本文链接:https://www.haomeiwen.com/subject/qmvkvdtx.html