Sqlsugar+vue2实现增删改查,分页查询,net6实现

学习记录,没有使用组件,用的原生组件,效果预览图如下

一、项目创建

如果启动错误大概率是连接字符串出错了,记住字符串内的是数据库名,而不是表名

1.创建项目使用ASP.NET Core Web API

 2.选择net6.0,把配置HTTPS取消

二、netcore后端

1.引入sqlsugarcore包

 2.创建SqlSugarHelper类来连接数据库

 public static class SqlSugarHelper
    {
        public static void Connection
            (this IServiceCollection services,
            IConfiguration configuration,
            string connect = "ConnectionString")
        {
            SqlSugarScope sqlSugarScope = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                ConnectionString = configuration[connect],
                IsAutoCloseConnection = true
            },
            db =>
            {
                //单例参数配置,所有上下文生效
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);//输出sql到控制台
                };
            });
            services.AddSingleton<ISqlSugarClient>(sqlSugarScope);
        }
    }

3.在appsettings.json内写入连接字符串,我把全文粘下来,文档数据库名为New_Demo

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionString": "Server=.;Database=New_Demo;Uid=sa;Pwd=123456;"
}

4.创建实体类Daily表

 public class Daily
    {
        /// <summary>
        /// 代办ID
        /// </summary>
        [SugarColumn(IsPrimaryKey = true)]
        public int Id { get; set; }

        /// <summary>
        /// 代办事项
        /// </summary>
        public string Title { get; set; }
    }

创建AddReq表,用于添加

 public class AddReq
    {
        public string Title { get; set; }
    }

创建Page表用于分页

 public class Page
    {
        public int PageIndex { get; set; } // 当前页码
        public int PageSize { get; set; } // 每页记录数
    }

5.创建控制器写接口

 [Route("api/[controller]/[action]")]//控制器的路由模板
    [ApiController]
    public class TodosController : Controller
    {
        //这段代码是一个ASP.NET Core控制器类的构造函数。
        //它使用依赖注入将一个名为db的ISqlSugarClient对象注入到控制器中,
        //以便在整个控制器的生命周期中都可以使用该数据库连接
        private readonly ISqlSugarClient db;
        public TodosController(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 获取
        /// </summary>
        [HttpGet]
        public List<Daily> Get()
        {
            //使用db.Queryable<todos>()方法从数据库中查询所有的todos记录,
            //并将结果保存在list变量中
            var list = db.Queryable<Daily>().ToList();
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<Daily>> GetUsers([FromQuery] Page page)
        {
            //创建了一个查询变量query,
            //使用db.Queryable<Daily>()生成一个查询对象
            //可以根据需要添加其他查询条件
            var query = db.Queryable<Daily>();
            //用于存储查询结果总数
            var totalCount = 0;

            //使用ToPageList方法对查询结果进行分页查询。
            //page.PageIndex表示当前页索引
            //page.PageSize表示每页的数据条目数量
            //totalCount是用于存储查询结果总数的引用
            var userList = query.ToPageList(page.PageIndex, page.PageSize, ref totalCount);

            // 返回结果
            //构造了一个包含totalCount和userList的匿名对象作为结果
            var result = new
            {
                TotalCount = totalCount,
                Items = userList
            };

            return Ok(result);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public bool Add(AddReq req)
        {
            try
            {
                Daily info = new Daily()
                {
                    //生成一个唯一的哈希码作为ID
                    Id = Math.Abs(Guid.NewGuid().GetHashCode()),
                    Title = req.Title
                };
                //检查数据库中是否已存在具有相同Title属性的记录
                if (db.Queryable<Daily>().Any(p => p.Title == req.Title))
                {
                    return false;
                }
                return db.Insertable(info).ExecuteCommand() > 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public bool Delete(int id)
        {
            try
            {
                int i =db.Deleteable<Daily>().Where(s => s.Id == id).ExecuteCommand();
                return i>0;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public bool DeleteAll(List<int> ints)
        {
            try
            {
                int rows = db.Deleteable<Daily>().In(ints).ExecuteCommand();

                return rows>0;
            }
            catch (Exception)
            {
                return false;
            }
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="todos"></param>
        /// <returns></returns>
        [HttpPut]
        public bool Update(int id, [FromBody] Daily model)
        {
            try
            {
                // 使用SqlSugar进行数据更新
                var result = db.Updateable<Daily>()
                    .SetColumns(m => new Daily
                    {
                        // 设置需要更新的字段
                        Title = model.Title,
                    })
                    .Where(m => m.Id == id)
                    .ExecuteCommand();

                return result > 0;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }

6.Program内

using api;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//应用程序构建后,不能修改ServiceCollection,所以这句话必须在build上面
builder.Services.Connection(builder.Configuration);


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())

{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.UseCors(t => t.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

三、vue前端首先需要安装node.js

1.官网Node.js (nodejs.org)

2.创建一个文件夹TodoDemo,打开后右键通过vscode打开

3.ctrl+shift+~打开终端,~就是esc下面那个

4.开始创建环境

vue create todos    创建todos根目录

选择vue2

 安装好之后执行以下操作

cd todos  命令,把终端移到todos下

npm  i   安装环境

npm run serve   启动

npm install vue-router@^3.5.1   路由

npm install vue-axios@^3.5.2

npm install [email protected] 

5.环境创建好之后,main.js内

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.config.productionTip = false

Vue.use(VueAxios, axios)

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

6.创建router文件,在内部创建index.js

import Vue from 'vue'

import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [

]

const router = new VueRouter({
  routes
})

export default router

7.App.vue内

<template>
  <section class="todo">
    <header>
      <h1>todos</h1>
      <input @keyup.enter="Addtodo" class="shu" v-model="form.title" placeholder="你要输入什么?" autofocus />
    </header>
    <section>
      <table style="width: 100%">
        <tbody>
          <tr v-for="item in tableData" :key="item.id">
            <td align="center">
              <input type="checkbox" :value="item.id" @change="Checkbox" />
            </td>
            <td align="center" height="50px">{
   
   { item.title }}</td>
            <td align="center">
              <button @click="del(item.id)">X</button>
            </td>
            <td align="center">
              <button @click="updateTitle(item.id)">修改</button>
            </td>
          </tr>
        </tbody>
      </table>
    </section>
    <footer>
      <button @click="deleteRows">清除选中项</button>
      <input  
        placeholder="你要修改成什么?"
        v-if="show"
        v-model="form.title"
        @keyup.enter="edit"
        autofocus />
    </footer>
    <div>
      <button @click="prevPage" :disabled="pageIndex === 1">上一页</button>
      <span>  {
   
   { pageIndex }}</span>
      <button @click="nextPage" :disabled="pageIndex === totalPage">下一页</button>
      <span>
        <select v-model="pageIndex" @change="goToPage">
          <option v-for="page in totalPage" :key="page">{
   
   { page }}</option>
        </select>
      </span><br>
      <span>总页数:{
   
   { totalPage }}</span><br>
      <span>总数据:{
   
   { totalCount }}</span>
    </div>
  </section>
</template>

<script>
export default {
  data() {
    return {
      selectedRows: [],
      form: {
        title: "",
      },
      show:false, //修改框的显示
      tableData: [],
      pageIndex: 1,//初始页数
      pageSize: 5,//每页数据数
      totalPage: 0,//页数
      totalCount:0,//数据数
      editid:0     //要修改的id值
    };
  },
  mounted() {
    // 初始化加载数据
    this.list();
  },
  methods: {
    //显示分页查询结果
    list() {
      // 发起请求获取数据
      this.axios
        .get("http://localhost:5200/api/Todos/GetUsers?PageIndex="+this.pageIndex+"&PageSize="+this.pageSize)
        .then((res) => {
          this.totalCount=res.data.totalCount;//数据总数量
          this.tableData = res.data.items;// 将每页5个数据绑定数据到数组
          this.totalPage =Math.ceil(res.data.totalCount / this.pageSize); // 总页数=数据总数/单页数据数,并向上取整
        })
        .catch((error) => {
          console.error(error);
        });
    },
    prevPage() {
      // 上一页
      if (this.pageIndex > 1) {
        this.pageIndex--;
        this.list();
      }
    },
    nextPage() {
      // 下一页
      if (this.pageIndex < this.totalPage) {
        this.pageIndex++;
        this.list();
      }
    },

    //通过下拉框到达指定页数
    goToPage() {
      this.axios
        .get("http://localhost:5200/api/Todos/GetUsers?PageIndex="+this.pageIndex+"&PageSize="+this.pageSize)
        .then((res) => {
          this.totalCount=res.data.totalCount;
          this.tableData = res.data.items;
          this.totalPage =Math.ceil(res.data.totalCount / this.pageSize);
        })
        .catch((error) => {
          console.error(error);
        });
    },
    //添加
    Addtodo(e) {
      //e:通常是一个事件对象,表示触发事件的事件对象
      //e.target:找到输入框input组件
      //e.target.value  找到组件后,进入方法获取输入框的值value
      const title = e.target.value.trim();//获取输入框的值并去除字符串两端的空白字符
      //检查title是否有值,为空停止
      if (!title) {
        return;
      }
      this.axios
        .post("http://localhost:5200/api/Todos/Add", this.form)
        .then((res) => {
          if (res.data) {
            this.list();
            this.form.title="";
          } else {
            console.log("error");
            return false;
          }
        });
    },
    //删除
    del(id) {
      this.axios
        .delete("http://localhost:5200/api/Todos/Delete?id=" + id)
        .then((res) => {
          if (res.data) {
            this.list();
          }
          else {
            console.log("error");
            return false;
          }
        });
    },
    //修改
    edit(e){
      const title = e.target.value.trim();
      if (!title) {
        return;
      }
      this.axios.put('http://localhost:5200/api/Todos/Update?id='+this.editid, this.form)
        .then((res) => {
          if (res.data) {
            this.show=false;
            this.form.title="";
            this.list();
          }
        })
        .catch(error => {
          console.error('标题修改失败:', error);
        });
    },
    //点击修改按钮,修改框显示并获得要修改的值的id
    updateTitle(id) {
      this.show=true;
      this.editid=id;
    },

    //多项删除的多选框
    Checkbox(event) {
      const rowId = event.target.value;//得到复选框的值
      //如果复选框被选中(checked为true)
      //它会将"rowId"添加到一个名为"selectedRows"的数组中。
      if (event.target.checked) {
        this.selectedRows.push(rowId);
      }
      //如果复选框未被选中(checked为false)
      //它会查找数组中是否存在"rowId"的索引。
      //如果存在,它将使用splice()方法来从数组中删除该索引处的元素
      else {
        const index = this.selectedRows.indexOf(rowId);
        if (index > -1) {
          this.selectedRows.splice(index, 1);
        }
      }
    },
    //多项删除
    deleteRows() {
      //判断"selectedRows"数组的长度是否大于0,以确保至少选择了一行
      if (this.selectedRows.length > 0) {
        this.axios
          .delete("http://localhost:5200/api/Todos/DeleteAll", {
            data: this.selectedRows,
          })
          .then((res) => {
            if (res.data) {
              this.list();
            }
          })
          .catch((error) => {
            console.log(error);
          });
      }
    },
  },
};

</script>

<style>
.todo {
  font-size: 30px;
  width: 500px;
  margin-left: 700px;
}
.todo h1 {
  text-align: center;
}
.shu {
  width: 500px;
  height: 30px;
}</style>

完成

猜你喜欢

转载自blog.csdn.net/Ronion123/article/details/132227361
今日推荐