我用的是vue js我正在尝试添加文本和下拉框内的html可编辑的div。
我想添加使用按钮的下拉框。此下拉菜单可以添加到文本的任何位置。就像我把光标放在哪里。
现在,它几乎工作,但我找不到一个问题。
当我输入并添加多个下拉列表,然后按下**“获取数据模型”按钮时,它总是显示我从下拉列表中选择的选项不正确。我的意思是它总是向我展示第一个选择。
使用此获取数据模型**按钮,我尝试获取所有文本+选择选项。
下面是我的代码:
<template>
<div>
<div class="content-editable" contenteditable="true" @input="onInput" ref="contentEditable"></div>
<button @click="addDropdown">Add Dropdown</button>
<button @click="getDataModel">Get Data Model</button>
<div>{{ dataModel }}</div>
</div>
</template>
<script>
export default {
data() {
return {
content: '',
dropdowns: [],
dropdownOptions: ['Option 1', 'Option 2', 'Option 3'],
dataModel: '',
};
},
methods: {
onInput(event) {
this.content = event.target.innerHTML.replace(/<div><br><\/div>/g, '');
},
addDropdown() {
const dropdown = {
selectedOption: this.dropdownOptions[0],
};
this.dropdowns.push(dropdown);
const editableDiv = this.$refs.contentEditable;
const dropdownSelect = document.createElement('select');
dropdownSelect.style.width = '100px';
this.dropdownOptions.forEach((option) => {
const dropdownOption = document.createElement('option');
dropdownOption.value = option;
dropdownOption.text = option;
dropdownSelect.appendChild(dropdownOption);
});
editableDiv.appendChild(dropdownSelect);
},
getDataModel() {
const editableDiv = this.$refs.contentEditable;
const clonedDiv = editableDiv.cloneNode(true);
const selectElements = clonedDiv.querySelectorAll('select');
this.dropdowns.forEach((dropdown, index) => {
const selectedOption = dropdown.selectedOption;
const selectedOptionText = Array.from(selectElements[index].options).find((option) => option.value === selectedOption)?.text;
const selectedOptionTextNode = document.createTextNode(` ${selectedOptionText}`);
selectElements[index].replaceWith(selectedOptionTextNode);
});
this.dataModel = clonedDiv.textContent;
},
},
};
</script>
<style scoped>
.content-editable {
border: 1px solid #ccc;
padding: 10px;
min-height: 100px;
margin-bottom: 10px;
}
</style>
字符串
1条答案
按热度按时间cbjzeqam1#
Vuejs是数据驱动的,MVVM认为,如果你想创建多个'input '标签请使用v-for更合理,而不是动态创建DOM
字符串
希望能帮到你!