Vue3$Data-Props

76 阅读1分钟

Vue3$Data-Props

1. What is Props

Props:传给组件的参数。

在 Vue 中,props 一般是数据 data。

Props 也可以是函数 function,但是一般的事件使用 emit。

我的风格是,和数据有关的函数作为 props 传进来。(这和 React 的风格一致,React 中没有 emit。)
对于和 props 无关的事件,通过 emit “发射出去”。

2. How to Use

1. 定义 Props

定义 props 的方式:

  1. 字符串(数组):['title']声明数据名称
  2. 键值对(对象):
    1. propName: String,名称:类型
    2. propName: [Number, String],名称:类型数组
    3. propName: {type: String, required: false, default: ''},名称:对象(注意,对象类型的 default 值 需要是工厂函数)
    4. propName: {validator(value, props) { return true },名称:校验规则
// `defineProps` is a compile-time macro that is only available inside `<script setup>`
const props = defineProps(['title'])
defineProps({
    greetingMessage: String,
    likes: [Number, String],
    propC: {
        type: String,
        required: true
    },
    propD: {
        type: Number,
        default: 100
    },
    propE: {
        // object / array
        type: Object,
        // defaults must be returned from a factory function.
        default: (rawProps) {
            return { message: 'hello' }
        }
    },
    propF: { 
        validator(value, props) { 
            return ['success', 'warning', 'danger'].includes(value)
        }
    },
    propG: {
	// Function with a default value
	type: Function,
	default() { return 'Default function' }
    }
})

2. 使用 Props

<MyComponent greeting-message="hello" /> // can also greetingMessage
<BlogPost v-bind="post" /> // post: {id: 1, title: "Post1"}

3. Caveat 注意事项

Props 是只读的 immutable。

为什么呢?就像我借你作业抄,你不能把我的答案改了。 如果你发现我的答案错了怎么办?告诉我,我来改。


这里的情况是:父组件定义了数据和操作数据的方法(data & functions),子组件接受它们。

就像是一个对象(设计者)里定义了数据和方法,使用者只需要使用这些数据和方法。

Links

VueProps