vue3.5正式上线,其中对父传子的props的操作(包括默认值在内)更加便捷,写法更加简便

237 阅读1分钟

1.之前常常在想,为什么vue3 的父传子中的props通过解构之后就不能是响应式的呢?非要用toRef()或者toRefs()去把解构出来失去响应式的数据重新变为响应式。为什么不能直接就写成是响应式的呢,不然就多了一道工序。

那么在vue3.5在9月3日的正式发布,在这么多的优化中,我一眼就看到了props传值解构的优化,也解开了我上面说到的疑惑。那么下面我将会给大家展示一下vue3.5之前的props传值解构和vue3.5之后的props传值解构有什么不一样

vue3.5之前

// 定义props去接受父组件传过来的数据
const props = defineProps({
  isShare:String
})


const {isShare} = props // 失去响应式的解构

// 继续保持响应式的解构
const {isShare} = toRef(props) // 或者用toRefs
// 或者
const testCount = toRef(props, 'testCount');

vue3.5之后对props的解构进行了优化

// 定义props去接受父组件传过来的数据

// 第一种解构方法
const {isShare} = defineProps({
  isShare:String
})
console.log('vue3.5之后的第一种解构的方法,我是响应式的哦',isShare);

// 第二种解构的方法
const props = defineProps({
  isShare:String
})
const {isShare} = props
console.log('vue3.5之后的第二种解构的方法,我是响应式的哦',isShare);

vue3.5还对props的默认值进行了优化

我们先看看vue3.5之前的默认传值

// 定义props去接受父组件传过来的数据

const props = defineProps({
  isShare:{
    type:String,
    default:false
  }
})

vue3.5之后的props默认值

// 定义props去接受父组件传过来的数据

const {isShare=false} = defineProps({
  isShare:{
    type:String,
  }
})

本人是新手前端,如果文章有写的不好的,麻烦各位大佬可以指导一下,谢谢