Vue3.5正式上线,父传子props用法更丝滑简洁

46,503 阅读2分钟

前言

Vue3.52024-09-03正式上线,目前在Vue官网显最新版本已经是Vue3.5,其中主要包含了几个小改动,我留意到日常最常用的改动就是props了,肯定是用Vue3的人必用的,所以针对性说一下props两个小改动使我们日常使用更加灵活。

image.png

一、带响应式Props解构赋值

简述: 以前我们对Props直接进行解构赋值是会失去响应式的,需要配合使用toRefs或者toRef解构才会有响应式,那么就多了toRefs或者toRef这工序,而最新Vue3.5版本已经不需要了。

这样直接解构,testCount能直接渲染显示,但会失去响应式,当我们修改testCount时页面不更新。

<template>
  <div>
    {{ testCount }}
  </div>
</template>

<script setup>
  import { defineProps } from 'vue';
  const props = defineProps({
    testCount: {
      type: Number,
      default: 0,
    },
  });

  const { testCount } = props;
</script>

保留响应式的老写法,使用toRefs或者toRef解构

<template>
  <div>
    {{ testCount }}
  </div>
</template>

<script setup>
  import { defineProps, toRef, toRefs } from 'vue';
  const props = defineProps({
    testCount: {
      type: Number,
      default: 0,
    },
  });

  const { testCount } = toRefs(props);
  // 或者
  const testCount = toRef(props, 'testCount');
</script>

最新Vue3.5写法,不借助”外力“直接解构,依然保持响应式

<template>
  <div>
    {{ testCount }}
  </div>
</template>

<script setup>
  import { defineProps } from 'vue';
  const { testCount } = defineProps({
    testCount: {
      type: Number,
    },
  });

</script>

相比以前简洁了真的太多,直接解构使用省去了toRefs或者toRef

二、Props默认值新写法

简述: 以前默认值都是用default: ***去设置,现在不用了,现在只需要解构的时候直接设置默认值,不需要额外处理。

先看看旧的default: ***默认值写法

如下第12就是旧写法,其它以前Vue2也是这样设置默认值

<template>
  <div>
    {{ props.testCount }}
  </div>
</template>

<script setup>
  import { defineProps } from 'vue';
  const props = defineProps({
    testCount: {
      type: Number,
      default: 1
    },
  });
</script>

最新优化的写法 如下第9行,解构的时候直接一步到位设置默认值,更接近js语法的写法。

<template>
  <div>
    {{ testCount }}
  </div>
</template>

<script setup>
  import { defineProps } from 'vue';
  const { testCount=18 } = defineProps({
    testCount: {
      type: Number,
    },
  });
</script>

小结

这次更新其实props的本质功能并没有改变,但写法确实变的更加丝滑好用了,props使用非常高频感觉还是有必要跟进这种更简洁的写法。如果那里写的不对或者有更好建议欢迎大佬指点啊。