const editor = new E('#content');报错无效的节点选择器

来源:8-9 文档管理页面布局修改

Tendernesz

2021-05-13

为什么我的editor,通过id选择器选择content的时候, const editor = new E(’#content’);这一句需要放到
onMounted中才有效,直接放到setup()中,页面加载的时候会报错,说无法找到这个id。这个是否和vue的生命周期有关系?
报错信息

完整代码

<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <a-row :gutter="24">
        <a-col :span="8">

          <p>
            <a-form layout="inline" :modal="param">
              <a-form-item>
                <a-button type="primary" @click="add">新增</a-button>
              </a-form-item>
            </a-form>
          </p>
          <a-table :columns="columns"
                   :data-source="level1"
                   :row-key="record => record.id"
                   :loading="loading"
                   :pagination="false"
          >

            <!--        <template #cover="{text: cover}">-->
            <!--          <img v-if="cover" :src="cover" alt="avatar" class="ant-avatar">-->
            <!--        </template>-->
            <template #name="{text,record}">
              {{record.sort}} {{text}}
            </template>
            <template v-slot:action="{text,record}">
              <a-space size="small">
                <a-button type="primary" @click="edit(record)" size="small">编辑</a-button>
                <a-popconfirm
                    :title="'删除后不可恢复,确认删除'+record.name+'?'"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="showDeleteConfirm(record)"
                >
                  <a-button type="danger" size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-col>
        <a-col :span="16">
          <p>
            <a-form layout="inline" :modal="param">
              <a-form-item>
                <a-button type="primary" @click="save">保存</a-button>
              </a-form-item>
            </a-form>
          </p>
          <a-form :model="doc" :label-col="{span:6}" :wrapper-col="{ span: 14 }" layout="vertical">
            <a-form-item>
              <a-input v-model:value="doc.name" :disabled="formDisabled" placeholder="名称"/>
            </a-form-item>
            <a-form-item>
              <a-tree-select
                  v-model:value="doc.parent"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeSelectData"
                  placeholder="请选择父文档"
                  tree-default-expand-all
                  :replaceFields="{children:'children', title:'name', key:'id', value: 'id'}"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model:value="doc.sort" :disabled="formDisabled" placeholder="排序"/>
            </a-form-item>
            <a-form-item>
              <div id="content"></div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

    </a-layout-content>
  </a-layout>
  <!--  <a-modal-->
  <!--      title='编辑'-->
  <!--      v-model:visible="modalVisible"-->
  <!--      :confirm-loading="modalLoading"-->
  <!--      @ok="save"-->
  <!--  >-->
  <!--  </a-modal>-->
</template>
<script lang="ts">
import {defineComponent, onMounted, ref, createVNode} from 'vue';
import {Modal} from 'ant-design-vue';
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import axios from "axios";
import {message} from 'ant-design-vue';
import {Tool} from "@/utils/tools";
import {useRoute} from "vue-router";
import E from 'wangeditor';

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    slots: {customRender: 'name'}
  },
  // {
  //   title: '名称',
  //   dataIndex: 'name',
  //   key: 'name',
  // },
  // {
  //   title: '父文档',
  //   dataIndex: 'parent',
  //   key: 'parent',
  // },
  // {
  //   title: '排序',
  //   dataIndex: 'sort',
  //   key: 'sort',
  // },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    slots: {customRender: 'action'}
  },
];


export default defineComponent({
  name: 'AdminDoc',
  setup() {
    const route = useRoute();
    // console.log('route:', route);
    // console.log('route.fullpath:', route.fullPath);
    // console.log('route.path:', route.path);
    // console.log('route.hash:', route.hash);
    // console.log('route.query:', route.query);
    // console.log('route.params:', route.params);
    // console.log('route.meta:', route.meta);

    const loading = ref(false);

    const docs = ref();
    /**
     * 一级文档树,children属性就是二级文档
     * [{
     *   id: "",
     *   name: "",
     *   children: [{
     *     id: "",
     *     name: "",
     *   }]
     * }]
     */
    const level1 = ref(); // 一级文档树,children属性就是二级文档
    level1.value = [];
    const treeSelectData = ref();
    treeSelectData.value = []

    /**
     * 数据查询
     * @param params
     */
    const param = ref();
    param.value = {};
    const handleQuery = (ebookId: any) => {
      loading.value = true;
      level1.value = []
      treeSelectData.value = []
      axios.get('/doc/list',).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          docs.value = data.content.list;
          console.log('原始数组:', docs.value);
          level1.value = []
          level1.value = Tool.array2Tree(docs.value, 0);
          console.log('树形结构数组:', level1.value);
          doc.value = {
            ebookId: route.query.ebookId,
          };
          treeSelectData.value = Tool.copy(level1.value);
          //为选择树添加一个"无"节点
          treeSelectData.value.unshift({id: 0, name: '无'});
        } else {
          message.error(data.message);
        }

      });
    };

    /**
     * 将某节点及其子孙节点全部设置为disabled
     */
    const setDisabled = (treeSelectData: any, id: any) => {
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          //如果当前节点就是目标节点,则设为disabled
          node.disabled = true;

          //遍历所有子节点,将子节点全部都设为disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              setDisabled(children, children[j].id);
            }
          }
        } else {
          //如果当前节点不是目标节点,再到其子节点再找找看
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisabled(children, id);
          }
        }
      }
    };


    //-----表单属性------
    const doc = ref({});
    //模态框是否显示
    const modalVisible = ref<boolean>(false);
    //模态框确认按钮是否显示正在加载
    const modalLoading = ref<boolean>(false);
    //表单是否可编辑
    const formDisabled = ref<boolean>(false);

    let editor: E;
    // const editor = new E('#content');

    /**
     * 编辑
     */

    const showEditModal = (record: any) => {
      modalVisible.value = true;
      doc.value = Tool.copy(record);
      treeSelectData.value = Tool.copy(level1.value);
      //为选择树添加一个"无"节点
      treeSelectData.value.unshift({id: 0, name: '无'});
      setDisabled(treeSelectData.value, record.id);

      console.log('treeSelectData', treeSelectData.value);

      // setTimeout(function () {
      //   //富文本编辑框
      //   editor = new E('#content');
      //   editor.config.zIndex = 0;
      //   editor.create();
      // }, 100);

    };

    /**
     * 打开新增窗口
     */
    const showAddModal = () => {
      modalVisible.value = true;
      doc.value = {
        ebookId: route.query.ebookId,
      };
      treeSelectData.value = Tool.copy(level1.value);
      //为选择树添加一个"无"节点
      treeSelectData.value.unshift({id: 0, name: '无'});

      // setTimeout(function () {
      //   //富文本编辑框
      //   editor = new E('#content');
      //   editor.create();
      // }, 100);
    };

    /**
     * 保存
     */
    const save = () => {
      modalLoading.value = true;
      formDisabled.value = true;
      axios.post('/doc/save', doc.value).then((response) => {
        const data = response.data;
        if (data.success) {
          modalVisible.value = false;
          formDisabled.value = false;
          modalLoading.value = false;
          message.success('保存成功');
          doc.value= {};
          // editor.destroy();
          //重新加载列表
          handleQuery(route.query.ebookId);
        } else {
          message.error(data.message);
          formDisabled.value = false;
          modalLoading.value = false;
        }

      });

    };


    //要删除的ids
    let deleteIds: Array<string> = [];
    let deleteNames: Array<string> = [];

    /**
     * 将某节点及其子孙节点全部添加到deleteIds
     */
    const getDeleteIds = (treeSelectData: any, id: any) => {
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          console.log('deleteId', node.id);
          //如果当前节点就是目标节点,则添加到deleteIds
          deleteIds.push(node.id);
          deleteNames.push(node.name);

          //遍历所有子节点,将子节点全部放到deleteIds
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getDeleteIds(children, children[j].id);
            }
          }
        } else {
          //如果当前节点不是目标节点,再到其子节点再找找看
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getDeleteIds(children, id);
          }
        }
      }
    };
    /**
     * 删除
     */
    const del = () => {
      axios.delete('/doc/delete/' + deleteIds.join(',')).then((response) => {
        const data = response.data;
        if (data.success) {
          // console.log('111',data.content[0].name);
          message.success('成功删除' + data.content[0].name + '下所有内容');
          //重新加载列表
          handleQuery(route.query.ebookId);

        } else {
          message.error(data.message);
        }
      });
    }
    /**
     * 删除二次确认
     */
    const showDeleteConfirm = (record: any) => {
      deleteIds = [];
      deleteNames = [];
      getDeleteIds(level1.value, record.id);
      Modal.confirm({
        title: '去人是否进行删除操作?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '本操作将删除[' + deleteNames + ']',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          del();
        },

      });
    };


    onMounted(() => {
      handleQuery(route.query.ebookId);
      // editor = new E('#content');
      editor.config.zIndex = 0;
      editor.create();
    });
    return {
      columns,
      // docs,
      level1,
      loading,


      modalVisible,
      modalLoading,
      doc,
      formDisabled,

      edit: showEditModal,
      save,
      add: showAddModal,
      del,

      handleQuery,
      param,
      treeSelectData,

      showDeleteConfirm,
    };
  },
});
</script>

<style scoped>
.ant-avatar {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border-radius: 8%;
  margin: 5px 0;
}
</style>
写回答

2回答

甲蛙

2021-05-14

确实是你说的生命周期的问题。可以这样理解:setup在执行的过程中,页面的元素都是没有的。所以凡是要用到页面元素的代码,都不能放在setup里,而应该放到onMounted里,onMounted就是等页面都渲染完成后,再去执行里面的代码

0
1
Tendernesz
非常感谢!
2021-05-14
共1条回复

慕粉174719507

2022-03-13

安装wangeditor的时候与课程的版本一致就没这么多问题了

npm i wangeditor@4.6.3 --save

下载视频          
0
0

Spring Boot+Vue3前后端分离,实战wiki知识库系统

一课掌握前后端最火框架,更有职场竞争力

2524 学习 · 1671 问题

查看课程