Vue3 父子传值

学习随笔(Vue3 父子传值)

  1. 父子传值,与2类似,但有些细节不同
<template>
  <div>
    父级
  </div>
  <hr>
  <!-- 子级 -->
  <son :title="name"></son>
</template>

<script setup lang='ts'>
import son from './components/son.vue'
let name = '我是父级'

</script>

父级传值跟2没有区别,但是子级接值就与2有所区别了,2使用props:{},而3使用defineProps(){}

<template>
  <div>
    子级
  </div>
  <div>
    值: {{ title }}
  </div>
</template>

<script setup lang='ts'>
const props = defineProps(){
  title:{
    type: String,
    default: '默认值---子级'
  }
}
//  在使用时,无法直接读取到title,需要将其赋值后才可以读到,但是页面中的读取不受影响
console.log('接收的值:', props.title);

// ts 有一种写法,叫做泛型自变量模式 代码量简单点
const props = defineProps<{
    title: string,
    arr:number[]
}>();
console.log('接收的值:', porps.title);

// 如果要定义默认的值,需要withDefaults,这个参数只能接受defineProps
withDefaults(defineProps<{
  title: string,
  arr:number[]
}>(),{
  // 如果定义复杂数据,需要写一个回调函数,防止引用
  arr: () => [123,456]
})

</script>

子传父值,同样使用emit,但是与vue2有所区别,使用defineEmits();

<script setup lang='ts'>
const emit = defineEmits(['on-click']);

const send = () => {
  emit('on-click', "圆子")
}
</script>
posted @ 2023-09-23 09:41  圆子同学  阅读(36)  评论(0)    收藏  举报