vue操作v-html内元素的示例代码
<template>
<div>
<el-row :gutter="20">
<el-col :span="24">
<div class="title-content bg-choice">
<span class="label-content"> 问题:</span>
<span v-html="getQuestion"> </span>
</div>
</el-col>
</el-row>
</div>
</template>
<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
@Component({
name: "FillBlank"
})
export default class extends Vue {
answerContent: string[] = [];
mounted() {
this.bindEvent();
}
// 给v-html内的元素绑定事件
bindEvent() {
const elements = document.getElementsByClassName("fill-blank");
for (let i = 0; i < elements.length; i++) {
const item = elements[i] as HTMLInputElement;
//事件动态绑定
item.onblur = this.fetchData;
}
}
fetchData() {
const elements = document.getElementsByClassName("fill-blank");
// 先清空答案
const answerContent = [];
// 获取全部填空题答案
for (let i = 0; i < elements.length; i++) {
const element = elements[i] as HTMLInputElement;
answerContent.push(element.value);
}
// 修改this.answerContent触发监听事件
this.answerContent = answerContent;
}
beforeDestroy() {
// 移除动态绑定事件
const elements = document.getElementsByClassName("fill-blank");
for (let i = 0; i < elements.length; i++) {
const item = elements[i] as HTMLElement;
// 移除动态绑定事件
item.onblur = null;
}
}
get getQuestion() {
return `根据项目采购合同谈判的阶段划分,项目采购管理中的合同谈判一般分为<el-input
class="answer-content fill-blank"
placeholder="请输入答案"
/>、<el-input
class="answer-content fill-blank"
placeholder="请输入答案"
/>和签约阶段。`;
}
@Watch("answerContent")
handleSave() {
console.log("answerContent: ", this.answerContent);
}
}
</script>
<style>
.label-content {
font-weight: bold;
margin-left: 20px;
}
.title-content {
border-radius: 4px;
min-height: 36px;
line-height: 36px;
}
.answer-content {
text-align: center;
-webkit-appearance: none;
background-color: #ffffff;
background-image: none;
border-radius: 4px;
border: 1px solid #dcdfe6;
box-sizing: border-box;
color: #1f2d3d;
display: inline-block;
font-size: inherit;
height: 40px;
line-height: 40px;
outline: none;
padding: 0 15px;
transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
width: 30%;
/* 去边框 */
border-radius: 0;
border-left: 0;
border-right: 0;
border-top: 0;
}
</style>