Sqlsugar+vue2 は追加、削除、変更、クエリ、ページング クエリ、net6 実装を実装します。

学習記録、コンポーネントは使用せず、ネイティブコンポーネントを使用、効果プレビューは次のとおりです

1. プロジェクトの作成

起動エラーがある場合は、接続文字列が間違っている可能性が高く、文字列にはテーブル名ではなくデータベース名が含まれることに注意してください。

1. ASP.NET Core Web APIを使用してプロジェクトを作成する

 2. net6.0を選択し、HTTPSの設定を解除します。

2.ネットコアバックエンド

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. エンティティクラスの日次テーブルの作成

 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; }
    }

ページング用のページテーブルを作成する

 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();

3. 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 runserve start

npm install vue-router@^3.5.1 ルーティング

npm インストール vue-axios@^3.5.2

npm インストール [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.ルーターファイルを作成し、内部的に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