把最近学习vue的一些知识点记录下来,今天记录一下Vue通过vue-resource连接数据库接口渲染列表和添加删除功能
首先我们得引入vue的版本文件和vue-resource.js,注意:vue-resource的引入要在vue版本文件之后
然后把列表页面写好,然后在methods里写一个获取列表数据的方法:
getAllList() { //获取所有的品牌列表
this.$http.get(‘api/getprodlist‘).then(result => {
var result = result.body
if (result.status === 0) {
this.list = result.message
} else {
alert(‘获取数据失败‘)
}
})
}
当然list是在data里面已经定义好的
data: {
name:‘‘,
list: [
{ id:1, name: ‘五菱宏光‘, ctime: newDate() },
{ id:2, name: ‘摩托罗拉‘, ctime: newDate() }
]
}
然后调用vue的生命周期函数里面的created()函数,调用此函数时当vm实例的data和methods初始化完毕后,vm实例会自动执行,在此函数里面调用刚刚写的getAllList()函数。此时列表就能获取到。添加和删除功能类似,需要注意的是删除的时候需要传入对应数据的id值,我们可以在url后面直接拼接。为了方便接口地址的修改操作,可以通过全局配置,请求数据接口的根域名和全局启用emulateJSON选项
Vue.http.options.root=‘http://www.liulongbin.top:3005/‘;
Vue.http.options.emulateJSON=true;
以下是全部代码:
Document//通过全局配置,请求数据接口的根域名
Vue.http.options.root=‘http://www.liulongbin.top:3005/‘;//全局启用emulateJSON选项
Vue.http.options.emulateJSON=true;var vm = newVue({
el:‘#app‘,
data: {
name:‘‘,
list: [
{ id:1, name: ‘五菱宏光‘, ctime: newDate() },
{ id:2, name: ‘摩托罗拉‘, ctime: newDate() }
]
},
created() {//当vm实例的data和methods初始化完毕后,vm实例会自动执行
this.getAllList()
},
methods: {
add() {//添加
this.$http.post(‘api/addproduct‘, { name: this.name }, { emulateJSON: true }).then(result =>{if (result.body.status === 0) {//成功
this.getAllList()this.name=‘‘}else{
alert(‘获取数据失败‘)
}
})
},
getAllList() {//获取所有的品牌列表
this.$http.get(‘api/getprodlist‘).then(result =>{var result =result.bodyif (result.status === 0) {this.list =result.message
}else{
alert(‘获取数据失败‘)
}
})
},
del(id){//删除
this.$http.get(‘api/delproduct/‘+id).then(result=>{if (result.body.status === 0) {//成功
this.getAllList()
}else{
alert(‘获取数据失败‘)
}
})
}
}
})
使用是记得引入对应的文件。
原文:https://www.cnblogs.com/Yaucheun/p/10823991.html