首先新建一個項目,而後引入iView插件,配置好routerjavascript
npm安裝iViewcss
npm install iview --save cnpm install iview --save
src/main.js
文件內容前端
import Vue from 'vue' import App from './App.vue' import router from './router' import iView from 'iview'; import 'iview/dist/styles/iview.css'; Vue.use(iView); Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
src/router.js
文件內容vue
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/table1', component: () => import('./views/table1.vue') }, { path: '/table2', component: () => import('./views/table2.vue') }, { path:'/', redirect:'/table1' } ] })
環境說明java
python版本:3.6.6 Django版本:1.11.8 數據庫:MariaDB 5.5.60
新建Django項目,在項目中新建app,配置好數據庫
api_test/app01/models.py
文件內容python
from django.db import models class UserProfile(models.Model): name = models.CharField("用戶名", max_length=32) email = models.EmailField(max_length=32) status = models.IntegerField(default=1) def to_dic(self): return dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]])
api_test/urls.py
文件內容ios
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^update_user/$',views.update_user), url(r'^get_user/$',views.get_user_list), ]
api_test/app01/views.py
文件內容vue-router
from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import UserProfile @csrf_exempt def update_user(request): request_dict = json.loads(request.body) user_id = request_dict.get("user_id") name = request_dict.get("name") email = request_dict.get("email") status = request_dict.get("status") try: UserProfile.objects.filter(id=int(user_id)).update(name=name, email=email, status=status) return JsonResponse({"result": True}) except Exception as e: return JsonResponse({"result": False}) def get_user_list(request): # for i in range(1, 1001): // 向數據庫建立1000條記錄 # name = "user" + str(i) # email = "user%s@qq.com" % str(i) # status = random.randint(1, 3) # user_obj = UserProfile(name=name, email=email, status=status) # user_obj.save() current = request.GET.get("current", 1) size = request.GET.get("size", 0) sortType = request.GET.get("sortType") filterType = request.GET.get("filterType") res_list = [] try: user_list = UserProfile.objects.all() if filterType and filterType != "undefined": user_list = user_list.filter(status=int(filterType)) total = user_list.count() if current and size: end = int(current) * int(size) start = (int(current) - 1) * int(size) user_list = user_list[start:end] except Exception as e: print(e) return JsonResponse({"result": False}, safe=False) for user in user_list: res_list.append(user.to_dic()) if sortType == "desc": res_list = sorted(res_list, key=lambda x: x["id"], reverse=True) else: res_list = sorted(res_list, key=lambda x: x["id"], reverse=False) res = { "data": { "list": res_list, "total": total }, "result": True } return JsonResponse(res, safe=False)
這裏前端向後端發送POST請求時,後端沒有執行csrftoken驗證,前端獲取csrftoken,後端進行csrftoken驗證不在本文示例以內數據庫
src/views/table1.vue
文件內容npm
<template> <div style="padding:32px 64px"> <h1>可編輯單元格</h1> <Table :columns="columns" :data="data" :loading="loading" border size="small"> </Table> <div style="text-align:center;margin:16px 0"> <Page :total="total" :current.sync="current" show-total @on-change="getData"></Page> </div> </div> </template> <script> import axios from 'axios' export default { data() { return { columns:[ { type:"index", width:100, align:'center', title:'ID', key:'id', }, { title:'用戶名', key:'name', render: (h, {row, index}) => { let edit; let control; if (this.editIndex === index) { edit = [h('Input', { props: { value: row.name }, on: { input: (val) => { this.editValue = val; } } })]; control = [ h('Icon', { style: { cursor: 'pointer', margin: '8px' }, props: { type: 'md-checkmark', size: 16, color: '#19be6b' }, on: { click: () => { this.data[index].name = this.editValue; this.editIndex = -1; axios.post(`http://127.0.0.1:8000/update_user/`,{ user_id: row.id, name: this.editValue, email: row.email, status: row.status }).then(res => { if(res.data.result) { this.$Message.success('修改用戶名成功'); } else { this.$Message.error('請求失敗'); } }) } } }), h('Icon', { style: { cursor: 'pointer', margin: '8px' }, props: { type: 'md-close', size: 16, color: '#ed4014' }, on: { click: () => { this.editIndex = -1; } } }) ] } else { edit = row.name; control = [h('Icon', { style: { cursor: 'pointer' }, props: { type: 'ios-create-outline', size: 16 }, on: { click: () => { this.editIndex = index; this.editValue = row.name; } } })] } return h('Row', [ h('Col', { props: { span: 16 } }, edit), h('Col', { props: { span: 6 } }, control) ]) } }, { title:'狀態', key:'status', render: (h, {row}) => { if (row.status === 1) { return h('Tag', { props: { color: 'green' } }, "等級 1") } else if (row.status === 2) { return h('Tag', { props: { color: 'red' } }, "等級 2") } else if (row.status === 3) { return h('Tag', { props: { color: 'blue' } }, "等級 3") } }, }, { title:'郵箱', key:'email', } ], data:[], loading:false, total:0, editIndex: -1, editValue: '', current:1, // 當前頁面 size:10, // 設置初始每頁能夠顯示的數據條數 } }, methods:{ getData (){ if (this.loading) return; this.loading = true; axios.get(`http://127.0.0.1:8000/get_user/?current=${this.current}&size=${this.size}`).then(res => { if(res.data.result) { this.data = res.data.data.list; this.total = res.data.data.total; this.loading = false } else { this.$Message.error('請求失敗'); } }) }, handleChangeSize (val){ this.size = val; this.$nextTick(() => { this.getData(); }) } }, mounted () { this.getData(); } } </script>
分別啓動先後端,用瀏覽器打開URL:http://localhost:8080/#/table1
,頁面渲染以下
點擊某一行用戶名後面的修改按鈕,用戶名原有數據會成input框,讓用戶輸入修改數據
當用戶修改完成,點擊保存,則會把修改後的用戶名發送到後端接口,保存到數據庫中
再次刷新瀏覽器,會看到用戶名已經修改了
src/views/table2.vue
文件內容
<template> <div style="padding:32px 64px"> <h1>可編輯行</h1> <Table :data="data" :columns="column" border></Table> <div style="text-align:center;margin:16px 0"> <Page :total="total" :current.sync="current" :page-size-opts="page_size_array" show-sizer show-total @on-change="getData" @on-page-size-change="handleChangeSize"></Page> </div> </div> </template> <script> import axios from 'axios' export default { data() { return { editIndex: -1, editName: '', editEmail: '', editStatus: '', statusArray: [ { key: '1', value: '1' }, { key: '2', value: '2' }, { key: '3', value: '3' }, ], column: [ { type:"index", width:100, align:'center', title:'ID', key:'id', }, { title: "用戶名", key: 'name', render: (h, {row, index}) => { let edit; if (this.editIndex === index) { this.editName = row.name edit = [h('Input', { props: { value: row.name }, on: { input: (val) => { this.editName = val; } } })] } else { edit = row.name; } return h('div', [edit]); } }, { title: "郵箱", key: 'email', render: (h, {row, index}) => { let edit; if (this.editIndex === index) { this.editEmail = row.email edit = [h('Input', { props: { value: row.email }, on: { input: (val) => { this.editEmail = val; } } })] } else { edit = row.email; } return h('div', [edit]); } }, { title: "等級", key: 'status', render: (h, {row, index}) => { let edit; if (this.editIndex === index) { this.editStatus = row.status let options = this.statusArray.map(v => { return h('Option',{ props: { value: v.value } }, v.key) }) edit = [h('Select', { props: { value: row.status }, on: { input: (val) => { this.editStatus = val; } } },options)] } else { edit = row.status; } return h('div', [edit]); } }, { title: "操做", render: (h, {row, index}) => { if (this.editIndex === index) { return [ h('Button', { props: { type: 'success' }, on: { click: () => { this.data[index].name = this.editName; this.data[index].email = this.editEmail; this.data[index].status = this.editStatus; this.editIndex = -1; axios.post(`http://127.0.0.1:8000/update_user/`,{ user_id: row.id, name: this.editName, email: this.editEmail, status: this.editStatus }).then(res => { if(res.data.result) { this.$Message.success('修改用戶名成功'); } else { this.$Message.error('請求失敗'); } }) } } }, '保存'), h('Button', { props: { type: 'error' }, style: { marginLeft: '6px' }, on: { click: () => { this.editIndex = -1; } } }, '取消') ] } else { return h('Button', { on: { click: () => { this.editName = row.name; this.editEmail = row.email; this.editStatus = row.status; this.editIndex = index; } } }, '修改') } } } ], data: [], loading:false, page_size_array: [10, 20, 30, 40, 60, 100], // 設置每頁能夠切換的條數 total:0, current:1, // 當前頁面 size:10, // 設置初始每頁能夠顯示的數據條數 }; }, methods:{ getData (){ if (this.loading) return; this.loading = true; axios.get(`http://127.0.0.1:8000/get_user/?current=${this.current}&size=${this.size}`).then(res => { if(res.data.result) { this.data = res.data.data.list; this.total = res.data.data.total; this.loading = false } else { this.$Message.error('請求失敗'); } }) }, handleChangeSize (val){ this.size = val; this.$nextTick(() => { this.getData(); }) } }, mounted () { this.getData(); } } </script>
用瀏覽器打開URL:http://localhost:8080/#/table2
,頁面渲染以下
點擊某一行操做欄中的修改
按鈕,用戶名和郵箱原有數據會成input框,input框中數據爲原數據,等級原有數據處會變成select下拉框讓用戶選擇
當用戶修改完成,點擊保存,則會把修改後的用戶信息經過POST請求發送到後端接口,保存到數據庫中
再次刷新瀏覽器,會看到用戶名已經修改了