实现一个可拖拽表格

基于vue框架

一、如何使用sortable.js

1、在组件中导入 import Sortable from 'sortablejs'

2、编写sortable函数,写好配置项

    sortable () {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sort = Sortable.create(el, {
        // 拖动切换动画持续时间
        animation: 1000,
        // 按住鼠标延迟多久才允许拖动
        dalay: 200,
        ghostClass: 'sortable-ghost',
        setData: function (dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          // console.log(evt);
        }
      })
    }

3、在mounted中调用sortable函数

  mounted () {
    this.sortable()
  },

4、sortable配置项详解

sortable.js中文文档 - itxst.com

二、如何使用mock.js

1、src中新建mock文件夹,创建mock.js文件,然后在main.js中引入文件

const Mock = require('mockjs')

const baseContent = '<p>I am testing data, I am testing data.</p><p><img src="https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943"></p>'
const image_uri = 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'

Mock.mock('/article', 'get', {
    code: 0,
    msg: "mock接口数据",
    // 返回含十个文章对象的数组
    "array|10": [
        {
            id: '@increment',
            timestamp: +Mock.Random.date('T'),
            author: '@first',
            reviewer: '@first',
            title: '@title(5, 10)',
            content_short: 'mock data',
            content: baseContent,
            forecast: '@float(0, 100, 2, 2)',
            importance: '@integer(1, 3)',
            'type|1': ['CN', 'US', 'JP', 'EU'],
            'status|1': ['published', 'draft'],
            display_time: '@datetime',
            comment_disabled: true,
            pageviews: '@integer(300, 5000)',
            image_uri,
            platforms: ['a-platform']
        }
    ]

})

2、在src中新建api文件夹,创建article,js ,暴露接口

import axios from "axios";

export const fetchArticle = () => {
  return axios.get('/article')
}

3、在组件中调用接口函数

  mounted () {
    this.getData()
  },
  methods: {
    async getData () {
      const res = await fetchArticle()
      console.log(res);
    }
  }

三、如何根据需求封装axios

1、使用axios.create创建axios实例,并配置请求拦截器,响应拦截器实现查看是否携带token,以及一些提示效果,这样一来,api中可直接使用配置好的axios发起请求

import axios from 'axios'
import { Message } from 'element-ui';
import { getToken } from '../utils/auth'

const service = axios.create({
  baseURL: '/getData',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 如果有token,请求头则携带token
    if (getToken()) {
      config.headers['Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error);
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 2000) {
      Message({
        type: 'error',
        message: "error",
        duration: 5 * 1000
      })
    }
    return res
  },
  error => {
    console.log(error);
    return Promise.reject(error)
  }
)

export default service

2、暴露api接口

import request from '../utils/request'

export const FetchToken = () => {
  return request({
    url: '/login',
    method: 'get'
  })
}

拖拽表格组件

<template>
  <div class="app-container">
    <!-- Note that row-key is necessary to get a correct row order. -->
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" width="65">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="Date">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="300px" label="Title">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column width="110px" align="center" label="Author">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" label="Importance">
        <template slot-scope="{row}">
          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="icon-star" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="Readings" width="95">
        <template slot-scope="{row}">
          <span>{{ row.pageviews }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="Status" width="110">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="Drag" width="80">
        <template slot-scope="{}">
          <svg-icon class="drag-handler" icon-class="drag" />
        </template>
      </el-table-column>
    </el-table>
    <div class="show-d">
      <el-tag>The default order :</el-tag> {{ oldList }}
    </div>
    <div class="show-d">
      <el-tag>The after dragging order :</el-tag> {{ newList }}
    </div>
  </div>
</template>

<script>
import { fetchList } from '@/api/article'
import Sortable from 'sortablejs'

export default {
  name: 'DragTable',
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data () {
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      sortable: null,
      oldList: [],
      newList: []
    }
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      this.listLoading = true
      const { data } = await fetchList(this.listQuery)
      this.list = data.items
      this.total = data.total
      this.listLoading = false
      this.oldList = this.list.map(v => v.id)
      this.newList = this.oldList.slice()
      this.$nextTick(() => {
        this.setSort()
      })
    },
    setSort () {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost {
  opacity: 0.8;
  color: #fff !important;
  background: #42b983 !important;
}
</style>

<style scoped>
.icon-star {
  margin-right: 2px;
}
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d {
  margin-top: 15px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值