vue+element ui+core+axios制做前端增刪改查

myvue.vue

<template>
  <div>
    <!-- <el-input v-model="state" placeholder="请输入内容" style="width:50%"></el-input> -->
    <el-input placeholder="请输入内容" v-model="state" style="width:30%">
      <i slot="prefix" class="el-input__icon el-icon-search"></i>
    </el-input>

    <!-- 顯示 -->
    <el-table
      :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
      border
      style="width: 54%;margin:auto;"
    >
      <el-table-column type="index" width="50" label="编号"></el-table-column>
      <el-table-column prop="userid" label="id" width="180"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="userage" label="年齡" align="right" sortable></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="drawer2 = true;choseEditItem(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteClick(scope.row.userid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加 -->
    <el-button type="success" @click="drawer = true">添加</el-button>
    <!-- :direction="direction" -->
    <el-drawer title="添加数据" :visible.sync="drawer" :before-close="handleClose">
      <el-form
        :model="userInfo"
        status-icon
        ref="userInfo"
        label-width="100px"
        class="demo-userInfo"
      >
        <el-form-item
          label="姓名"
          prop="username"
          :rules="[
      { required: true, message: '姓名不能为空'},
    ]"
        >
          <el-input v-model="userInfo.username" autocomplete="off" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item
          label="年龄"
          prop="userage"
          :rules="[
      { required: true, message: '年龄不能为空'},
      { type: 'number', message: '年龄必须为数字值'}
    ]"
        >
          <el-input type="userage" v-model.number="userInfo.userage" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="addClick()" style="width:200px; margin-top:400px">提交</el-button>
          <el-button @click="resetForm('userInfo')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 修改 -->
    <el-drawer title="修改数据" :visible.sync="drawer2">
      <el-form ref="form" :model="editItem" label-width="80px">
        <el-form-item label="名字">
          <el-input v-model="editItem.username" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="年齡">
          <el-input v-model="editItem.userage" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="editClick()" style="width:200px; margin-top:400px">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      small
      layout="prev, pager, next"
      :total="20"
      :page-size="pagesize"
    ></el-pagination>
  </div>
</template>
<script>
export default {
  name: "Gaojivue",
  data() {
    return {
      drawer: false,
      drawer2: false,
      direction: null,
      items: null,
      //初始显示的列表
      tableData: [],
      //排序显示
      state: null,
      pagesize: 5,
      currentPage: 1,
      //添加显示
      userInfo: {
        userid: 0,
        username: "",
        userage: ""
      },
      //修改后显示的列表
      editItem: {}
    };
  },
  watch: {
    state(val) {
      this.initData();
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭?")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    //搜索
    initData() {
      var items = [];
      for (let i = 0; i < this.items.length; i++) {
        const item = JSON.parse(JSON.stringify(this.items[i]));
        if (this.state && item.username.indexOf(this.state) == -1) {
          continue;
        }
        items.push(item);
      }
      this.tableData = items;
    },

    //查
    getJoke() {
      var that = this;
      this.$axios({
        url: "http://localhost:57850/weatherforecast",
        methods: "get"
      }).then(
        function(response) {
          console.log(response.data);
          that.items = response.data;
          that.initData();
          //这是从本地请求的数据接口,
          // that.userInfo = res.body;
        },
        function(err) {}
      );
    },

    //添加
    addClick() {
      var that = this;
      this.userInfo.userage = Number(this.userInfo.userage);
      this.$axios
        .post("http://localhost:57850/weatherforecast", this.userInfo)
        .then(res => {
          console.log(res);
          // this.$alert("添加成功");
          this.$message({
            type: "success",
            message: "添加成功!"
          });
          that.getJoke();
          this.drawer = false;
        });
    },
     resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    cancelForm() {
      this.drawer = false;
      this.drawer2 = false;
      clearTimeout(this.timer);
    },
    //刪除
    deleteClick(userid) {
      var id = parseInt(userid);
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .delete(`http://localhost:57850/weatherforecast?userid=${id}`)
            .then(res => {
              console.log(res);
              this.getJoke();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            });
          // console.log(res);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //修改
    choseEditItem(item) {
      this.editItem = item;
    },
    editClick() {
      var that = this;
      this.editItem.userage = Number(this.editItem.userage);
      this.$confirm("是否修改该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .put("http://localhost:57850/weatherforecast", this.editItem)
            .then(res => {
              console.log(res);
              this.getJoke();
              this.$message({
                type: "success",
                message: "修改成功!"
              });
              this.drawer2 = false;
            });
          // console.log(res);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改"
          });
        });
    },

    // 分页
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleCurrentChange: function(currentPage) {
      // debugger;
      this.currentPage = currentPage;
      console.log(this.currentPage); //点击第几页
      this.getJoke();
    }
  },
  created: function() {
    this.getJoke();
  }
};
</script>



<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

App.vue

<template>
  <div id="app">
    <router-view/>
    <router-link :to="items.url"> <el-button type="danger" plain>初級vue</el-button></router-link>
    <router-link :to="items2.url"><el-button type="info" plain>返回首页 </el-button></router-link>
    <router-link :to="items3.url"><el-button type="warning" plain>中級vue</el-button> </router-link>
  </div>
</template>

<script>
export default {
  name: 'App',
  data(){
    return{
      items:{url:"/Demovue"},
      items2:{url:"/"},
      items3:{url:"/Zhongjivue"}
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Demovue from '@/components/Demovue'
import Zhongjivue from '@/components/Zhongjivue'
import Axios from 'axios'

Vue.prototype.$axios = Axios //调用时使用this. $axios()
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/Demovue',
      name: 'Demovue',
      component: Demovue
    },
    {
      path: '/Zhongjivue',
      name: 'Zhongjivue',
      component: Zhongjivue
    }

  ]
})

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI);

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

core的Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NPoco;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddControllersWithViews().AddNewtonsoftJson(options =>
            //{
            //    // 忽略循环引用
            //    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //    // 不使用驼峰
            //    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
            //});

            //json字符串大小写原样输出
            services.AddMvc().AddJsonOptions(opt =>
            {
                opt.JsonSerializerOptions.PropertyNamingPolicy = null;
            });
            services.AddScoped<IDatabase>(x =>
            {
                return new Database("Server=127.0.0.1;Uid=root;Pwd=123456;Database=users;Charset=utf8mb4;", DatabaseType.MySQL, MySql.Data.MySqlClient.MySqlClientFactory.Instance);
            });
            // 开启跨域 https://www.cnblogs.com/linyijia/p/12981830.html
            services.AddCors(o =>
                o.AddPolicy("CorsPolicy",
                    builder => builder
                     .AllowAnyHeader().AllowAnyMethod().AllowCredentials().SetIsOriginAllowed(p => true)
                ));
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            // 跨域
            app.UseCors("CorsPolicy");

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

core主界面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NPoco;

namespace WebApplication1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IDatabase _database;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IDatabase database)
        {
            _database = database;
            _logger = logger;

        }
        /// <summary>
        /// 查看
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<usertable> Get()
        {
            var _users = _database.Fetch<usertable>("select * from usertable");
            return _users;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="item"></param>
        [HttpPost]
        public void post(usertable item)
        {
            _database.Insert(item);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        [HttpDelete]
        public void delete(int userid)
        {
            _database.Delete<usertable>("WHERE userid=@0", userid);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="item"></param>
        [HttpPut]
        public void update(usertable item)
        {
            _database.Update<usertable>("Set username=@username ,userage=@userage WHERE userid=@userid", item);
            //_database.Update(item);
        }
    }
}

实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1
{
    [NPoco.TableName("usertable")]
    public class usertable
    {
        public int userid { get; set; }
        public string username { get; set; }
        public int userage { get; set; }
    }
}

效果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本门课程重实战,将基础知识拆解到项目里,让你在项目情境里学知识。 这样的学习方式能让你保持兴趣、充满动力,时刻知道学的东西能用在哪、能怎么用。 平时不明白的知识点,放在项目里去理解就恍然大悟了。   一、融汇贯通 本视频采用了前后端分离的开发模式,前端使用Vue.js+Element UI实现了Web页面的呈现,后端使用Python 的Django框架实现了数据访问的接口,前端通过Axios访问后端接口获得数据。在学习完本章节后,真正理解前后端的各自承担的工作。   二、贴近实战 本系列课程为练手项目实战:学生管理系统v4.0的开发,项目包含了如下几个内容:项目的总体介绍、基本功能的演示、Vuejs的初始化、Element UI的使用、在Django中实现针对数据的增删改查的接口、在Vuejs中实现前端增删改查的调用、实现文件的上传、实现表格的分页、实现导出数据到Excel、实现通过Excel导入数据、实现针对表格的批量化操作等等,所有的功能都通过演示完成、贴近了实战   三、课程亮点 在本案例中,最大的亮点在于前后端做了分离,真正理解前后端的各自承担的工作。前端如何和后端交互   适合人群: 1、有Python语言基础、web前端基础,想要深入学习Python Web框架的朋友; 2、有Django基础,但是想学习企业级项目实战的朋友; 3、有MySQL数据库基础的朋友  

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值