对于数据的增删改查,需要用到axios
安装json-server
1、执行如下命令,安装json-server
npm install -g json-server
2、执行如下命令,检查json-server是否安装成功:
json-server -h
成功如下:
image.png
3、新建json文件,如:user.json(模拟数据)
{
"user":[
{
"id":"1",
"username":"甲",
"gender":"男",
"age":"18"
},
{
"id":"2",
"username":"乙",
"gender":"女",
"age":"20"
},
{
"id":"3",
"username":"丙",
"gender":"男",
"age":"28"
},
{
"id":"4",
"username":"丁",
"gender":"男",
"age":"30"
}
]
}
4、在控制台执行如下命令,启动json-server服务器
json-server user.json
操作
1、获取数据:
export default {
data(){
return{
userData:[],
}
},
mounted(){
this.getData();
},
methods:{
getData(){
this.$axios({
methods: 'get',
url: 'http://localhost:3000/user',
})
.then((data)=>{
this.userData = data;
console.log(this.userData)
})
.catch(function (error) {
})
}
}
}
image.png
image.png
2、获取指定id的数据
export default {
data(){
return{
userData:[],
}
},
mounted(){
this.getData();
},
methods:{
getData(){
this.$axios({
methods: 'get',
url: 'http://localhost:3000/user/1',//1为数据的id
})
.then((data)=>{
this.userData = data;
console.log(this.userData)
})
.catch(function (error) {
})
}
}
}
image.png
3、增加一条数据(点击按钮添加):
添加
export default {
data(){
return{
userData:[],
}
},
mounted(){
this.getData();
},
methods:{
// 获取原有的数据
getData(){
this.$axios({
methods: 'get',
url: 'http://localhost:3000/user',
})
.then((data)=>{
this.userData = data;
console.log(this.userData)
})
.catch(function (error) {
})
},
//点击按钮增加一条数据
addData(){
this.$axios({
method:"post",
url:"http://localhost:3000/user",
data:{
id:"5",
username:"张三",
gender:"男",
age:"22"
}
})
//获取增加后的数据
this.getData();
}
}
}
image.png
image.png
image.png
4、修改部分数据
添加
export default {
data(){
return{
userData:[],
}
},
mounted(){
this.getData();
},
methods:{
// 获取原有的数据
getData(){
this.$axios({
methods: 'get',
url: 'http://localhost:3000/user',
})
.then((data)=>{
this.userData = data;
console.log(this.userData)
})
.catch(function (error) {
})
},
//根据id,修改部分数据
changeData(){
this.$axios({
method:"patch",//修改部分数据
// method:"put",//修改全部数据
url:"http://localhost:3000/user/5",//5为要修改数据的id
data:{username:"魏无羡"}
})
//获取修改后的数据
this.getData();
},
}
}
image.png
image.png
image.png
5、删除数据
添加
export default {
data(){
return{
userData:[],
}
},
mounted(){
this.getData();
},
methods:{
// 获取原有的数据
getData(){
this.$axios({
methods: 'get',
url: 'http://localhost:3000/user',
})
.then((data)=>{
this.userData = data;
console.log(this.userData)
})
.catch(function (error) {
})
},
//点击按钮删除数据
deleteData(){
this.$axios({
method:"delete",
url:"http://localhost:3000/user/4",//4为要删除数据的id
})
//获取删除后的数据
this.getData();
},
}
}
image.png
image.png
image.png
附:
常用的url的形式有:
全部数据: localhost:3000/list
指定id: localhost:3000/list/1
指定条件: localhost:3000/list?name=李四&name=张三
模糊查询: localhost:3000/list?q=张