这时 :vue.extend 就有了合理的出场机会。
① inputBox => 双击后出现的输入框组件;
② textBox => 双击已是输入框的,或点保存,还原的文本组件;
③ changeBox => 是将 上面两个组件导入 ,继承并暴露出去;
④ tableBox => 通过new changeBox 暴露的继承组件 ,实现功能。
- <template>
- <input class="inputBox" v-model="value" />
- template>
- <script>
- export default {
- props: {
- value: String || Number,
- }
- }
- script>
- <template>
- <div class="cell">{{ value }} div>
- template>
- <script>
- export default {
- props: {
- value: String || Number,
- },
- };
- script>
- import Vue from "vue";
- import inputBox from "./inputBox.vue";
- import textBox from "./textBox.vue";
-
- const inputItem = Vue.extend(inputBox);
- const textItem = Vue.extend(textBox);
- export default {
- inputItem,
- textItem,
- }
采用 element - ui 的表格 ,方便双击 ,找到对应的 dom 【不用自己手写】
table.vue最后表格组件代码整合:
- <template>
- <div class="pageBox">
- <el-table
- :data="tableData"
- size="mini"
- class="tableBox"
- @cell-dblclick="dblclick"
- >
- <el-table-column
- v-for="item in columns"
- :key="item.prop"
- :prop="item.prop"
- :label="item.label"
- />
- el-table>
- <el-button @click="keepAll">保存el-button>
- div>
- template>
- <script>
- import changeBox from "./changeBox";
- export default {
- data() {
- return {
- columns: [
- { prop: "name", label: "姓名" },
- { prop: "height", label: "身高" },
- ],
- tableData: [
- { name: "张三", height: "180cm" },
- { name: "李四", height: "185cm" },
- ],
- };
- },
- methods: {
- dblclick(row, column, cell) {
- let to = cell.children[0];
-
- if (to.className.includes("inputBox")) {
- this.changeText(to.value, to);
- } else {
- this.changeInput(cell.innerText, to);
- }
- },
-
- changeInput(value, to) {
- new changeBox.inputItem({ propsData: { value: value } }).$mount(to);
- },
- changeText(value, to) {
- new changeBox.textItem({ propsData: { value: value } }).$mount(to);
- },
-
- keepAll() {
- //遍历dom ,修改虚拟dom
- let inputList = document.getElementsByClassName("inputBox");
- [...inputList].forEach((item) => {
- let text = item.value;
- this.changeText(text, item);
- });
- },
- },
- };
- script>