在组件props
传递的过程中,善用params
,这样可以先打通组件属性传递通道,对后续拓展非常有利。以本次评论组件举例,此处有 CommentItem
,CommentInput
,SubmitBtn
三层嵌套,分别对应评论组件、评论输入框与点击提交按钮。由 CommentItem
传入params
与post-comment-api
,由输入框进行输入获取与校验,由提交按钮进行api
调用,获取调用结果。如果不使用params
传参,例如,CommentItem
中传递// ** in CommentItem
const sumbitReplyComment = (commentText: string) => {
// 提交回复, posi api
api('submit', commentText);
}
<CommentInput :commentText="commentText" :sumbitComment="sumbitReplyComment "/>
// ** in CommentInput
<SubmitBtn :commentText="props.commentText" :postApi="props.sumbitReplyComment "/ >
// ** in SubmitBtn
const submitHandler = () => {
props.postApi(props.commentText);
}
<button @click="submitHandler" />
当传递数据需要增加字段时,需要不断增加传递字段,修改内容非常多。// ** in CommentItem
const sumbitReplyComment = (params : {commentText: string}) => {
// 提交回复, posi api
api('submit', params);
}
<CommentInput :params="{commentText}" :sumbitComment="sumbitReplyComment "/>
// ** in CommentInput
<SubmitBtn :commentText="{...props.params, commentText: value}" :postApi="props.sumbitReplyComment "/ >
// ** in SubmitBtn
const submitHandler = () => {
props.postApi(props.params);
}
<button @click="submitHandler" />
采用params
传递的方式,可以非常方便的拓展字段。