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