Development of editing function to find the feeling of writing code

Posted by tyrol_gangster on Thu, 03 Feb 2022 12:30:20 +0100

Write in front

I lost sleep again last night. I didn't sleep until 4:30. I also had two bad dreams. I woke up at 8:30. I feel so tired. I really want to get drunk. I can't. I'm afraid of drunk driving, ha ha ha.

There are still many things to do this year. You must take action. Just try your best. The rest depends on the will of God.

Task Disassembly

The front-end page has been drawn in the previous article, so now is the process of writing back-end logic, that is, the saving function after editing. The disassembly is as follows:

  • Add back-end save interface
  • When you click save, call the save interface
  • Save successfully refreshed the list

Implementation of editing function

1. Add back-end save interface

The same is the two step. First, we call it in controller first and second in service.

First, you need to add the call save method in the controller. The example code is as follows:

    /**
     * Save or update operation
     *
     * @param eBookSaveReq
     * @return
     */
    @PostMapping("/save")
    public CommonResp save(@RequestBody EBookSaveReq eBookSaveReq) {
        CommonResp resp = new CommonResp<>();
        eBookService.save(eBookSaveReq);
        return resp;
    }

Similarly, we implement it in service. The example code is as follows:

   /**
     * Save or update operation
     * @param eBookSaveReq
     */
    public void save(EBookSaveReq eBookSaveReq) {
        EBook eBook = copy(eBookSaveReq, EBook.class);
        if(ObjectUtils.isEmpty(eBook.getId())){
            //We didn't find it in the database, so we need to add it
            eBookMapper.insert(eBook);
        }else{
            //It is found in the database that there is this information. Go to the editing operation
            eBookMapper.updateByPrimaryKey(eBook);
        }
    }

Knowledge points:

EBookSaveReq is a copy of the entity Ebook in the domain. The EBookReq in the early code let me change it to EBookQueryReq, which is only used for query. The advantage of doing so is special-purpose. Some people may say, isn't this code redundancy? It's really a personal habit.

EBook eBook = copy(eBookSaveReq, EBook.class);, This code is a single copy. Students who don't understand it can refer to it Finding the feeling of writing code (7): encapsulating request parameters and return parameters This article.

2. When clicking save, call the save method, save successfully and refresh the list

After the back-end logic is written, we can use PostMan to test whether the interface is available locally. Here, I will call the test directly in the page.

At this time, we need to modify the method when clicking save. The example code is as follows:

<template>
  <a-layout class="layout">
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', minHeight: '280px' }">
      <a-table :columns="columns"
               :row-key="record => record.id"
               :data-source="ebooks1"
               :pagination="pagination"
               :loading="loading"
               @change="handleTableChange"
      >
        <template #cover="{ text: cover }">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>
        <template #name="{ text: name  }">
          <a>{{ text }}</a>
        </template>
        <template #customTitle>

      <span>
        <smile-outlined/>
        Name
      </span>
        </template>
        <template #action="{ record }">
      <span>
        <a-space size="small">
            <a-button type="primary" @click="edit(record)">
              edit
            </a-button>
             <a-modal
                 v-model:visible="modalVisible"
                 cancelText="cancel"
                 okText="preservation"
                 title="Edit eBook"
                 :confirm-loading="modalLoading"
                 @ok="handleModalOk"
             >
              <a-form
                  :model="ebooks_data"
                  name="basic"
                  :label-col="{ span: 4 }"
                  :wrapper-col="{ span: 16 }"
              >
              <a-form-item label="cover">
                <a-input v-model:value="ebooks_data.cover"/>
              </a-form-item>

                <a-form-item label="name">
                <a-input v-model:value="ebooks_data.name"/>
               </a-form-item>
                <a-form-item label="Category I">
                <a-input v-model:value="ebooks_data.category1Id"/>
                </a-form-item>
                 <a-form-item label="Category II">
                <a-input v-model:value="ebooks_data.category2Id"/>
                </a-form-item>
                <a-form-item label="describe">
                <a-input v-model:value="ebooks_data.description"/>
               </a-form-item>
                <a-form-item label="Number of documents">
                <a-input v-model:value="ebooks_data.docCount"/>
              </a-form-item>
                <a-form-item label="Reading number">
                <a-input v-model:value="ebooks_data.viewCount"/>
              </a-form-item>
                <a-form-item label="Number of likes">
                <a-input v-model:value="ebooks_data.voteCount"/>
              </a-form-item>
            </a-form>
            </a-modal>
             <a-button type="danger">
                delete
              </a-button>
          </a-space>
      </span>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>

</template>
<script lang="ts">
import {DownOutlined, SmileOutlined} from '@ant-design/icons-vue';
import {defineComponent, onMounted, reactive, ref, toRef} from 'vue';
import axios from 'axios';
import {message} from 'ant-design-vue';

export default defineComponent({
  name: 'AdminEbook',
  setup() {
    //Data binding using ref
    const ebooks = ref();
    // Data binding using reactive
    const ebooks1 = reactive({books: []})
    const pagination = ref({
      current: 1,
      pageSize: 2,
      total: 0
    });
    const loading = ref(false);
    const columns = [
      {
        title: 'cover',
        dataIndex: 'cover',
        width: 120,
        height: 120,
        slots: {customRender: 'cover'}
      },
      {
        title: 'name',
        dataIndex: 'name'
      },
      {
        title: 'Category I',
        dataIndex: 'category1Id',
        key: 'category1Id',
      },
      {
        title: 'Category II',
        dataIndex: 'category2Id',
        key: 'category2Id',
      },
      {
        title: 'describe',
        dataIndex: 'description',
        key: 'description',
      },
      {
        title: 'Number of documents',
        dataIndex: 'docCount'
      },
      {
        title: 'Reading number',
        dataIndex: 'viewCount'
      },
      {
        title: 'Number of likes',
        dataIndex: 'voteCount'
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    /**
     * Data query
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // If you do not clear the existing data, then click Edit after saving and reloading the data, and the data before editing will still be displayed in the list
      ebooks.value = [];
      axios.get("/ebook/list", {
        params: {
          page: params.page,
          size: params.size,
          name: params.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          const data = response.data;
          ebooks.value = data.content.list;
          ebooks1.books = data.content.list;
          // Reset paging button
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }
      });
    };


    /**
     * Triggered when the page number of the table is clicked
     */
    const handleTableChange = (pagination: any) => {
      console.log("Look at the paging parameters:" + pagination);
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize
      });
    };


    const ebooks_data = ref();
    const modalVisible = ref<boolean>(false);
    const modalLoading = ref<boolean>(false);
    /**
     * Edit / save
     */
    const handleModalOk = () => {
      modalLoading.value = true;
      axios.post("/ebook/save", ebooks_data.value).then(response => {
        const data = response.data;
        if (data.success) {
          modalVisible.value = false;
          modalLoading.value = false;
          //Reload list
          handleQuery({
            page: 1,
            size: pagination.value.pageSize,
          });
        }
      })

    };
    const edit = (record: any) => {
      modalVisible.value = true;
      ebooks_data.value = record;
    };


    onMounted(() => {
      handleQuery({
        page: 1,
        size: pagination.value.pageSize,
      });
    })
    return {
      modalVisible,
      modalLoading,
      handleModalOk,
      pagination,
      handleTableChange,
      loading,
      columns,
      edit,
      ebooks_data,
      ebooks1: ebooks,
      ebooks2: toRef(ebooks1, "books")
    }
  },
  components: {
    SmileOutlined,
    DownOutlined,
  },
});
</script>
<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>

Knowledge points:

  • The declaration of responsive variables runs through the whole process and needs to be used slowly;
  • The input parameter is a json object, so you need to add @ RequestBody in the controller
  • When using the table component, @ change="handleTableChange" needs to be added, and handleTableChange is the method to realize paging jump
  • The front-end code also needs to be handled well, which makes people look less uncomfortable. At least, I'm ashamed, because my variable declaration and use are embarrassing everywhere

3. Compile and run to see the effect

Write at the end

If you are idle and bored and have nothing to do, it is recommended to study or do what you are not good at. In this way, time will pass quickly. You will not be a slave of emotion, but only a happy little attendant.

This editing function has been developed. If you are interested, please try it yourself!

Stick to it, in fact, you are the great God!

Topics: Spring Boot Vue