使用场景:编程式动态创建Vue组件,并挂载在指定文档位置。
1.utils.js定义create组件的公共方法
Component - vue组件
props - props传参,父传子
/**
* @param Component 组件实例的选项对象
* @param props 组件实例中的prop
*/
create(Component, props) {
const comp = new (Vue.extend(Component))({ propsData: props }).$mount();
document.body.appendChild(comp.$el);
comp.remove = () => {
document.body.removeChild(comp.$el);
comp.$destroy();
};
return comp;
},
2. Vue组件ReplyInput.vue定义:
<template>
<van-popup
v-model="isShowAddComment"
position="bottom"
:overlay="true"
:style="{ height: 'auto' }"
>
<van-field
ref="commentInputNode"
v-model="comments"
clearable
:placeholder="placeholder"
>
<template #button>
<van-button plain size="small" type="info" @click="addComment"
>发送</van-button
>
</template>
</van-field>
</van-popup>
</template>
<script>
import { addComment } from "../../../api/api";
export default {
name: "ReplyInput",
components: {},
props: {
data: {
type: Object,
default: function () {
return {};
},
},
isReply: {
type: Boolean,
default: function () {
return false;
},
},
keyName: {
type: String,
default: function () {
return "";
},
},
commentType: {
type: Number,
default: function () {
return 0; // 0-报告评论 1-操作记录评论
},
},
},
data() {
return {
isShowAddComment: true,
comments: "",
};
},
mounted() {
this.$nextTick(() => {
this.$refs.commentInputNode.focus();
});
},
methods: {
/**
* 新增评论
*/
addComment() {
// 获取请求参数comments
let param = {
commentType: this.commentType,
commentDataId: this.data.id,
commentContent: this.comments,
};
// 回复 - 回复人id
if (this.isReply) {
param.commentDataId = this.data.commentDataId;
param.replyUserId = this.data.creatorId;
}
// 发送请求
addComment(param).then((resp) => {
if (this.$utils.isSuccess(resp)) {
// 组装评论,报告列表数据刷新
let commentData = resp.data.data.commentInfo.create;
if (this.isReply) {
commentData.replyUserLabel = this.data.creatorLabel;
}
this.$bus.emit(this.keyName + this.data.projectStage, commentData);
}
this.isShowAddComment = false;
});
},
},
created() {
if (this.isReply) {
this.placeholder = `回复 ${this.data.creatorLabel}:`;
} else {
this.placeholder = "评论";
}
},
};
</script>
<style lang="less" scoped>
.report-list-item {
}
</style>
3. 调用create方法,动态创建Vue组件并挂载在document位置
import ReplyInput from "@/components/projectDetails/projectReport/ReplyInput.vue";
export default {
name: "FeedBackListItem",
props: {
data: {
type: Object,
default: function () {
return {};
},
},
},
data() {
return {
isShow: true,
replyInput: null,
};
},
methods: {
showComment() {
// 不能回复自己的评论
if (this.$store.state.userId != this.data.creatorId) {
if (this.replyInput) {
this.replyInput.remove();
}
this.replyInput = this.$utils.create(ReplyInput, {
data: this.data,
keyName: this.$route.name,
isReply: true,
commentType: this.data.commentType, // 操作记录
});
}
},
},
mounted() {
// 设置当前所处的BD阶段
},
created() {},
};