跟着官网学 Vue - Props

  1. Props 的声明: 组件需要显式声明它所接受的 props。可以使用 props 选项来定义,可以是一个字符串数组,也可以是一个对象。

    // 使用字符串数组声明 props
    props: ['foo']
    
    // 使用对象声明 props,可以指定类型和其他选项
    props: {
      title: String,
      likes: Number,
      isPublished: {
        type: Boolean,
        required: true
      }
    }
    
  2. Prop 名字格式: 推荐使用 camelCase 形式,但在模板中使用 kebab-case 形式,以保持和 HTML 属性的一致性。

    // 推荐使用 camelCase 形式
    props: ['greetingMessage']
    
    // 在模板中使用 kebab-case 形式
    <MyComponent greeting-message="Hello" />
    
  3. 传递 Props: 可以通过静态或动态方式传递 props。使用 v-bind 或缩写 : 来进行动态绑定。

    <!-- 静态传递 -->
    <BlogPost title="lfsun with Vue" />
    
    <!-- 动态传递 -->
    <BlogPost :title="post.title" />
    
  4. 单向数据流: Props 遵循单向数据流,子组件不能直接修改父组件传递的 props。任何需要更改的数据应该通过触发事件来通知父组件。

  5. Prop 校验: 可以通过 props 选项的对象形式进行更细致的校验。提供类型和其他选项来确保传入的 props 满足预期。

    props: {
      propA: Number,
      propB: [String, Number],
      propC: {
        type: String,
        required: true
      },
      // ...
    }
    
  6. 运行时类型检查: Vue 组件支持对传入的 props 进行类型检查,以及自定义的校验函数。这有助于提高组件的可靠性。

    props: {
      author: Person
    }
    
  7. Boolean 类型转换: 对于声明为 Boolean 类型的 props,有特定的类型转换规则。例如,<MyComponent disabled /> 等同于传递 :disabled="true"

    props: {
      disabled: Boolean
    }
    

下面是一个完整的代码案例,演示了上述概念:

<!-- ParentComponent.vue -->

<template>
  <div>
    <ChildComponent :title="postTitle" :likes="postLikes" :is-published="isPostPublished" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      postTitle: 'lfsun with Vue',
      postLikes: 42,
      isPostPublished: true
    };
  }
}
</script>
<!-- ChildComponent.vue -->

<template>
  <div>
    <h2>{
   
   { title }}</h2>
    <p>Likes: {
   
   { likes }}</p>
    <p v-if="isPublished">Published</p>
    <p v-else>Not Published</p>
  </div>
</template>

<script>
export default {
  props: {
    title: String,
    likes: Number,
    isPublished: Boolean
  }
}
</script>

在这个例子中,ParentComponent 通过动态绑定的方式将数据传递给 ChildComponent 的 props。ChildComponent 接收这些 props 并在模板中显示相关信息。

猜你喜欢

转载自blog.csdn.net/qq_43116031/article/details/134982817