[TOC]

你可以基于对象的语法使用以下选项:

  • type:可以是下列原生构造函数中的一种:String、Number、Boolean、Array、Object、Date、Function、Symbol、任何自定义构造函数、或上述内容组成的数组。会检查一个 prop 是否是给定的类型,否则抛出警告。
  • default:any 为该 prop 指定一个默认值。如果该 prop 没有被传入,则使用这个值。对象或数组的默认值必须从一个工厂函数返回
  • required:Boolean 定义该 prop 是否是必填项。在非生产环境中,如果这个值为 truthy 且该 prop 没有被传入的,则一个控制台警告将会被抛出。
  • validator:Function 自定义验证函数会将该 prop 的值作为唯一的参数代入。在非生产环境下,如果该函数返回一个 falsy 的值 (也就是验证失败),一个控制台警告将会被抛出。你可以在这里查阅更多 prop 验证的相关信息。
  // businessData: {
//   type: Object as PropType<BusinessData>,
//   default: function () {
//     return {
//       labelSelected: null, //选择的 Label
//       labelOptions: [], // Label 可选项
//       keyOptions: [], // Key 可选项
//       attrLists: [
//         {
//           keySelected: null,
//           valueSelected: { selected: [] },
//           valuePageNum: 1,
//           valueOptions: []
//         }
//       ] // 属性列表
//     }
//   },
//   required: true
// }

单向数据流

所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。

vue不推荐直接在子组件中修改父组件传来的props的值,会报错
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “result” (found in component )

子组件可通过以下方式间接修改父组件传递的props

  1. 父组件通过 prop 传递来一个初始值;这个子组件将其另存为一个本地的 data property 数据来使用

    props: ['initialCounter'],
    data() {
    return {
    editInitialCounter: this.initialCounter
    }
    }
    
  2. prop 以一种原始的值传入且需要进行转换。在这种情况下,最好使用这个 prop 的值来定义一个计算属性:

    props: ['size'],
    computed: {
    normalizedSize() {
     return this.size.trim().toLowerCase()
    }
    }
    


    子组件视图动态响应Props

如果不使用watch来监听父组件传递的prop,子组件中另存的data property不会随着父组件传递的prop进行改变,因为另存为data property时,仅仅只是定义一个初始值。

props: ['initialCounter'],
data() {
  return {
    editInitialCounter: this.initialCounter
  }
}
watch: {
  initialCounter(newVal,oldVal){
      this.editInitialCounter = newVal
  }
}

props 的 TS 类型标注

PropType 注解 Props

Vue 对定义了 type 的 prop 执行运行时验证。要将这些类型提供给 TypeScript,我们需要使用 PropType 指明构造函数:

import { defineComponent, PropType } from 'vue'

interface Book {
  title: string
  author: string
  year: number
}

const Component = defineComponent({
  props: {
    name: String,
    id: [Number, String],
    success: { type: String },
    callback: {
      type: Function as PropType<() => void>
    },
    book: {
      // 提供一个比 `Object` 更具体的类型
      type: Object as PropType<Book>,
      required: true
    },
    metadata: {
      type: null // metadata 的类型是 any
    }
  }
})