props
注意:props 为单向数据流,从父组件流子组件,所以不应该在子组件中修改 props。
如有需要:
- 用另一个属性接收该 prop 的初始值;
- 基于该 prop 定义一个计算属性;
- 向父组件抛出一个事件。
声明
使用字符串数组:
1 2 3
| <script setup> const props = defineProps(['foo']); </script>
|
使用对象:
1 2 3 4 5 6
| <script setup> const props = defineProps({ title: String, likes: Number }); </script>
|
静态 prop
除了静态字符串,都应该使用变量进行传递。
1 2 3 4 5 6 7 8 9 10 11 12 13
| <BlogPost title="this is a title" />
<BlogPost :likes="post.likes" />
<BlogPost :is-published="post.isPublished" />
<BlogPost :ids="post.ids" />
<BlogPost :author="post.author" />
|
一个对象绑定多个 prop
使用无参数的 v-bind,而不是 :prop-name
1 2 3 4
| const post = { id: 1, title: "this is title", };
|
1
| <BlogPost v-bind="post" />
|
prop 校验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| defineProps({ propA: [String, Number], propB: { type: String, required: true, default: 'defaultVal' }, propC: { type: Object, default(rawProps) { return { message: 'hello' } } }, propD: { validator(value) { return ['success', 'warning', 'danger'].includes(value) } }, propE: { type: Function, default() { return 'Default function' } } });
|
Boolean 类型转换
1 2 3
| defineProps({ disabled: Boolean });
|
使用时:
1 2 3 4 5
| <MyComponent disabled></MyComponent>
<MyComponent></MyComponent>
|
emit
事件校验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <script setup> const emit = defineEmits({ click: null,
submit: ({ email, password }) => { if (email && password) { return true; } else { console.warn('Invalid submit event payload!') return false; } } });
function submitForm(email, password) { emit('submit', { email, password }); } </script>
|