今天看了下thinkjs(v2.1.7),做了一个简单的入门demo,基于mysql数据库增删改查,详细源码如下:

页面整体展示:

会员新增:

删除:

查询:

主页面:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>crud测试</title>
<link rel="stylesheet" type="text/css" href="/static/lib/jquery-easyui-1.4.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="/static/lib/jquery-easyui-1.4.3/themes/icon.css">
<script type="text/javascript" src="/static/lib/jquery-easyui-1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="/static/lib/jquery-easyui-1.4.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="/static/lib/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="/static/js/moment.js"></script>
<script src="/static/lib/jquery-file-upload/js/vendor/jquery.ui.widget.js"></script>
<script src="/static/lib/jquery-file-upload/js/jquery.iframe-transport.js"></script>
<script src="/static/lib/jquery-file-upload/js/jquery.fileupload.js"></script>
</head>
<body> <table id="dg" title="会员管理" style="width:100%;height:450px" class="easyui-datagrid" fitColumns="true" pagination="true" rownumbers="true"
url="/index/list" toolbar="#tb" data-options="pageSize:10,pageList:[5,10,15,25,50,100]">
<thead>
<tr>
<th field="cb" checkbox="true" align="center"></th>
<th data-options="field:'id',width:100">id</th>
<th data-options="field:'name',width:130,align:'center'">name</th>
<th data-options="field:'pass',width:130,align:'center'">pass</th>
<th data-options="field:'email',width:130,align:'center'">email</th>
<th data-options="field:'image',width:130,align:'center'">image</th>
<th data-options="field:'phone',width:130,align:'center'">phone</th>
<th data-options="field:'addr',width:130,align:'center'">addr</th>
<th data-options="field:'regtime',width:130,align:'center',formatter:formatReg">regtime</th>
<th data-options="field:'birth',width:130,align:'center'">birth</th>
<th data-options="field:'remark',width:130,align:'center'">remark</th>
<th field="operate" width="150" align="center" data-options="formatter:formatOperate">操作</th>
</tr>
</thead>
</table> <div id="tb"> <div style="margin-top: 5px;margin-bottom: 5px;">
<a href="javascript:openUserAddDialog()" class="easyui-linkbutton"
data-options="plain:true,iconCls:'icon-user_add'" plain="true">添加</a>
<a href="javascript:delNums()" class="easyui-linkbutton"
data-options="plain:true,iconCls:'icon-user_delete'" plain="true">删除</a>
</div>
<div style="margin-top: 5px;">
<table>
<tr>
<td align="right">会员编号:</td>
<td align="right"><input class="easyui-numberbox" id="s_id" size="20" style="width: 150px;"></td>
<td align="right">手机号:</td>
<td align="right"><input class="easyui-numberbox" id="s_phone" size="20" style="width: 150px;"></td>
<td align="right">姓名:</td>
<td align="right"><input class="easyui-textbox" id="s_name" size="20" style="width: 150px;"></td>
<td align="right"><a href="javascript:searchUser()" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-2012092109942'">查询</a></td>
</tr>
</table>
</div>
</div> <div id="dlg" class="easyui-dialog" style="width: 680px;height:630px;padding: 5px 5px" closed="true" buttons="#dlg-buttons" data-options="modal:true"
overflow-y="scroll">
<form id="addVipForm" method="post">
<table style="margin: 5px 5px;" cellspacing="5px">
<tr>
<td align="right" style="width: 140px;">手机号:</td>
<td align="left">
<input id="phone" name="phone" type="text" class="easyui-validatebox" data-options="required:true"
style="width: 150px;">
</td>
<td align="left">&nbsp;</td>
</tr>
<tr>
<td align="right" style="width: 140px;">姓名:</td>
<td align="left">
<input id="name" type="text" name="name" class="easyui-validatebox" data-options="required:true"
style="width: 150px;"></span>
</td>
<td align="left">&nbsp;</td>
</tr>
<tr>
<td align="right" style="width: 140px;">地址:</td>
<td align="left">
<input id="addr" name="addr" type="text" class="easyui-validatebox" style="width: 150px;" data-options="required:true">
</td>
<td align="left">&nbsp;</td>
</tr>
<tr>
<td align="right" style="width: 140px;">邮箱:</td>
<td align="left">
<input id="email" type="text" name="email" class="easyui-validatebox" style="width: 150px;" data-options="required:true,validType:'email'">
</td>
<td align="left">&nbsp;</td>
</tr>
<tr>
<td align="right" style="width: 140px;">头像:</td>
<td align="left">
<input type="file" id="file_upload"/>
<input type="hidden" id="file_path" name="image"/>
</td>
<td align="left">&nbsp;</td>
</tr>
<tr>
<td valign="top" align="left" style="width: 140px;">&nbsp;</td>
<td align="left">
<img id="newImg" style="width: 100px;height: 110px;" src="/static/img/default.gif">&nbsp;<span id="errMsg" style="color: red"></span>
</td>
<td align="left">&nbsp;</td>
</tr>
<tr>
<td align="right" style="width: 140px;">简介:</td>
<td align="left">
<textarea rows="10" cols="65" id="remark" name="remark" placeholder="请简要描述您的专业经验"></textarea>
</td>
</tr>
</table>
</form>
</div>
<div id="dlg-buttons">
<a href="javascript:save()" class="easyui-linkbutton" iconCls="icon-ok" plain="true">提交</a>
<a href="javascript:cancel()" class="easyui-linkbutton" iconCls="icon-cancel" plain="true">取消</a>
</div> <script type="text/javascript">
var url;
jQuery("#file_upload").fileupload({
iframe: true,
dataType: 'json',
url: "/index/upload",//文件上传地址,当然也可以直接写在input的data-url属性内
done: function (e, result) {
jQuery("#newImg").attr("src",result.result.path);
jQuery("#file_path").val(result.result.path);
}
});
function formatOperate(value, row, index){
var del = '<a onclick="del('+row.id+')" href="javascript:void(0)">删除</a>';
var update = '<a onclick="openUpdateDialog('+index+')" href="javascript:void(0)">修改</a>';
return update+ "&nbsp;" + del;
}
function del(id){
jQuery.messager.confirm("系统提示","您确认要删除该地区吗?",function(r){
if(r){
jQuery.post("/index/del",{id:id},function(result){
if(result.succ){
jQuery.messager.show({title:"提示",msg:"删除成功!"});
jQuery("#dg").datagrid("reload");
}else{
jQuery.messager.show({title:"提示",msg:"删除失败!"});
}
},"json");
}
});
}
function formatReg(value, row, index){
if(value)return moment(value).format("YYYY-MM-DD HH:mm:ss");
}
function openUserAddDialog(){
jQuery("#addVipForm").form("reset");
jQuery("#file_upload").attr("name","uploadFile");
jQuery("#dlg").dialog("open").dialog("setTitle", "新增会员");
url = "/index/add";
}
function save(){
jQuery("#addVipForm").form("submit", {
url: url,
onSubmit: function (param) {
if (!jQuery(this).form("validate")) {
return false;
}
jQuery("#file_upload").removeAttr("name");
return true;
},
success: function (result) { //result返回为String类型,需用eval函数处理为Object型对象再判断
result = JSON.parse(result);
if (result.succ) {
jQuery.messager.show({title:"提示",msg:"操作成功"});
jQuery("#addVipForm").form("reset");
jQuery("#dlg").dialog("close");
jQuery("#dg").datagrid("reload");
} else {
jQuery.messager.show({title:"提示",msg:"操作失败"});
}
}
});
}
function dispValue(row){
jQuery("#phone").val(row.phone);
jQuery("#name").val(row.name);
jQuery("#addr").val(row.addr);
jQuery("#email").val(row.email);
jQuery("#remark").val(row.remark);
if(row.image){
jQuery("#image").val(row.image);
jQuery("#newImg").attr("src",row.image);
}
}
function openUpdateDialog(index){
jQuery("#file_upload").attr("name","uploadFile");
var row = jQuery("#dg").datagrid('getData').rows[index];
jQuery("#dlg").dialog("open").dialog("setTitle", "修改");
url = "/index/update?id="+row.id;
dispValue(row);
}
function searchUser(){
var s_id = jQuery("#s_id").numberbox("getValue");
var s_phone = jQuery("#s_phone").numberbox("getValue");
var s_name = jQuery("#s_name").textbox('getText').trim();
jQuery("#dg").datagrid("load", {
"id": s_id,
"phone": s_phone,
"name": s_name
});
}
function delNums(){
var selectedRows=jQuery("#dg").datagrid('getSelections');
if(selectedRows.length==0){
jQuery.messager.show({title:"提示",msg:"请选择要删除的数据!"});
return;
}
var strIds=[];
for(var i=0;i<selectedRows.length;i++){
strIds.push(selectedRows[i].id);
}
var ids=strIds.join(",");
jQuery.messager.confirm("系统提示","您确认要删除这<span style='color: red'>"+selectedRows.length+"</span>条数据吗?",function(r){
if(r){
jQuery.post("/index/del",{id:ids},function(result){
if(result.succ){
jQuery.messager.show({title:"提示",msg:"删除成功"});
jQuery("#dg").datagrid("reload");
}else{
jQuery.messager.show({title:"提示",msg:"删除失败"});
}
},"json");
}
});
}
</script>
</body>
</html>

index.js控制器代码:

'use strict';

import Base from './base.js';
import fs from "fs";
import path from "path"; export default class extends Base {
/**
* index action
* @return {Promise} []
*/
async indexAction() {
//let model = this.model("user");
//console.log(model.pk);
//let data = await model.select();
//console.log(data);
//console.log(this.config("type"));
//this.navType = "home";
//let insertId = await model.add({last_name: "ddd1",first_name: "xxx1",userName: "xxx1", password: "yyy1"});
//console.log(insertId);
//let affectedRows = await model.where({id: "17"}).update({userName: "admin@thinkjs.org"});
//console.log(affectedRows);
//let result = await model.thenAdd({userName: "admin@thinkjs.org"}, {id: "17"});
//let result = await model.where({userName: "admin@thinkjs.org"}).update({userName: "admin"})
// let model = this.model("user");
//let result = await model.where({id: ["=", 10]}).delete();
//let sql = "select * from t_user where id=16";
//let result = yield model.query(sql);
//console.log(result);
//this.assign("name","test art-template");
return this.display();
};
async index2Action(){
return this.display();
};
async listAction(){
let posts = this.post();
let whereObj = {};
for (let prop in posts) {
if (posts.hasOwnProperty(prop) && posts[prop] && prop != "page" && prop != "rows") {
whereObj[prop] = posts[prop];
}
}
let userModel = this.model("user");
let data = await userModel.field("id,name,pass,email,image,phone,addr,regtime,birth,remark").where(whereObj).page(this.post("page"),this.post("rows")).countSelect();
this.json({"total":data.count,"rows":data.data});
};
async delAction(){
let userModel = this.model("user");
let posts = this.post("id");
let delNums = userModel.where({id: ['IN', posts]}).delete();
if(delNums){
this.json({"succ":true});
}else{
this.json({"succ":false});
}
};
async addAction(){
let userModel = this.model("user");
let values = this.post();
let id = userModel.add(values);
if(id){
this.json({"succ":true});
}else{
this.json({"succ":false});
}
};
async uploadAction(){
let file = think.extend({}, this.file('uploadFile'));
let filepath = file.path;
//文件上传后,需要将文件移动到项目其他地方,否则会在请求结束时删除掉该文件
let uploadPath = think.RESOURCE_PATH + '/static/upload';
think.mkdir(uploadPath);
let basename = path.basename(filepath);
fs.renameSync(filepath, uploadPath + '/' + basename);
this.json({path: '/static/upload/' + basename});
};
async updateAction(){
let userModel = this.model("user");
let nums = userModel.where({id: this.get("id")}).update(this.post());
if(nums){
this.json({"succ":true});
}else{
this.json({"succ":false});
}
}
}

src/common/config/db.js设置:

'use strict';
/**
* db config
* @type {Object}
*/
export default {
type: 'mysql',
log_sql: true,
log_connect: true,
adapter: {
mysql: {
host: '192.168.20.132',
port: '',
database: 'test',
user: 'root',
password: 'root',
prefix: 't_',
encoding: 'utf8'
},
mongo: { }
}
};

再记录下修改thinkjs模板引擎为art-template:

首先创建名为art的适配器:

thinkjs adapter template/art

执行完成后,会创建文件 src/common/adapter/template/art.js。扩展缓存类需要实现如下的方法:

其次修改src/common/config/view.js:

这样在页面中便可以直接使用art模板了。。。

源代码:https://github.com/caiya/proj_es6

thinkjs crud练习的更多相关文章

  1. 【翻译】MongoDB指南/CRUD操作(四)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...

  2. 【翻译】MongoDB指南/CRUD操作(三)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...

  3. 【翻译】MongoDB指南/CRUD操作(二)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...

  4. 【翻译】MongoDB指南/CRUD操作(一)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...

  5. 【原】无脑操作:express + MySQL 实现CRUD

    基于node.js的web开发框架express简单方便,很多项目中都在使用.这里结合MySQL数据库,实现最简单的CRUD操作. 开发环境: IDE:WebStorm DB:MySQL ------ ...

  6. Hibernate(4)——主键生成策略、CRUD 基础API区别的总结 和 注解的使用

    俗话说,自己写的代码,6个月后也是别人的代码……复习!复习!复习!涉及的知识点总结如下: hibernate的主键生成策略 UUID 配置的补充:hbm2ddl.auto属性用法 注解还是配置文件 h ...

  7. 学习SpringMVC——你们要的REST风格的CRUD来了

    来来来,让一下,客官,您要的REST清蒸CRUD来了,火候刚刚好,不油不腻,请慢用~~~ 如果说前面是准备调料,洗菜,切菜,摆盘,那么今天就来完整的上道菜,主要说的是基于REST风格实现数据的增删改查 ...

  8. Elasticsearch的CRUD:REST与Java API

    CRUD(Create, Retrieve, Update, Delete)是数据库系统的四种基本操作,分别表示创建.查询.更改.删除,俗称"增删改查".Elasticsearch ...

  9. ASP.NET Core Web API Cassandra CRUD 操作

    在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将 ...

随机推荐

  1. OI计算几何 简单学习笔记

    学习平面几何,首先我们要会熟练地应用向量,其次也要知道一些基本的几何知识.(其实看看数学课本就可以了吧) 因为是看的蓝书,所以很多东西做了引用.(update:还参考了赵和旭dalao的讲义) 下面先 ...

  2. day9学python 类+异常处理+初识socket

    类+异常处理+初识socket 类的特点: 1.封装-同其他语言 2.继承 py2 经典类深度优先 新式类类名(object)广度优先py3 都是广度优先 3.多态-python本身无多态 可用方法调 ...

  3. toggleClass,toggle切换

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. HTML中DOM元素的子节点为空?!firstChild, lastChild, childeNodes[]为空

  5. Sublime Text3 最新版3207 安装及破解

    注:原文地址 https://www.abbeyok.com/archives/337 Sublime Text 3最近更新了新版本,最新版本:3207,之前的license无效了,新版破解方法如下: ...

  6. jmeter性能测试指标

    1.jp@gc - Actiive Threads Over Time:不同时间的活动用户数量展示(图表) 当前的时间间隔是1毫秒,在setting中可以设置时间间隔以及其他的参数 2.jp@gc - ...

  7. 2016级算法第三次上机-E.ModricWang's Polygons

    930 ModricWang's Polygons 思路 首先要想明白,哪些多边形可能是格点正多边形? 分情况考虑: 三角形不可能,因为边长为有理数的正三角形的面积为无理数,而格点三角形的面积为有理数 ...

  8. POJ_3468 A Simple Problem with Integers 【线段树区间查询+修改】

    一.题目 POJ3468 二.分析 裸的线段树区间查询+修改. 三.AC代码 #include <cstdio> #include <iostream> #include &l ...

  9. @RequestMapping的value属性

    package com.zby.controller; import javax.servlet.http.HttpServletRequest; import org.springframework ...

  10. 推荐-Everything搜索工具

    简介: windows操作系统下极其强大的文件搜索工具. 下载: https://www.voidtools.com/downloads/ 推荐理由: 速度之快难以想象,日常工作必备工具之一. 发现的 ...