封装notebooks api
import request from '@/helpers/request';
const URL = {
GET: '/notebooks',
ADD: '/notebooks',
UPDATE: '/notebooks/:id',
DELETE: '/notebooks/:id'
}
export default {
getAll() {
return request(URL.GET, 'GET')
},
addNotebook({title=''} = {title: ''}){
return request(URL.ADD, 'POST', {title})
},
updateNotebook(id: number, {title=''} = {title: ''}){
return request(URL.UPDATE.replace(':id', id.toString()), 'PATCH', {title} )
},
delete(id: number){
return request(URL.DELETE.replace(':id', id.toString()), 'DELETE')
}
}
函数参数
{title='a'} = {title: 'b'}
表示如果函数没有传参数,则默认参数为{title: 'b'}
, 如果传的参数对象里没有title属性,则title属性默认值为a
从外部文件引入scss
<style lang="scss" scoped>
@import '~@/assets/css/notebook-list.scss';
</style>
实现笔记本的创建修改删除
onCreate() {
const title = window.prompt('创建笔记本')
if(title !== null && title.trim() === ''){
window.alert('笔记本名不可为空')
}
if(title !== null && title.trim() !== ''){
Notebooks.addNotebook({title}).then((res: any) => {
window.alert(res.msg)
this.notebooks.unshift(res.data)
}).catch(err => window.alert(err.msg))
}
}
onEdit(notebook: Notebook) {
const title = window.prompt('修改笔记本', notebook.title)
if(title !== null && title.trim() === ''){
window.alert('笔记本名不可为空')
}
if(title !== null && title.trim() !== ''){
Notebooks.updateNotebook(notebook.id,{title}).then((res: any) => {
window.alert(res.msg)
notebook.title = title
}).catch(err => window.alert(err.msg))
}
}
onDelete(notebook: Notebook) {
const isConfirm = window.confirm('确定要删除吗?')
if(isConfirm){
Notebooks.delete(notebook.id)
.then((res: any) =>{
window.alert(res.msg)
this.notebooks.splice(this.notebooks.indexOf(notebook), 1)
}
).catch(err => window.alert(err.msg))
}
}
时间格式转化
```typescript const friendlyDate = (date: Date) => { const dateObj = typeof date === ‘object’ ? date : new Date(date) const time = dateObj.getTime() const now = Date.now() const space = now - time let str
switch(true) { case space< 60000:
str = '刚刚'
break
case space < 1000*3600:
str = Math.floor(space / 60000) + '分钟前'
break
case space < 1000360024:
str = Math.floor(space/(1000*3600)) + '小时前'
break
default:
str = Math.floor(space/(1000*3600*24)) + '天前'
} return str }
export {friendlyDate}
使用时间转化函数
```typescript
getAll() {
return new Promise((resolve, reject)=> {
request(URL.GET, 'GET').then((res:any) => {
res.data = res.data.sort((a: Notebook,b: Notebook) => {
if(a.createdAt === b.createdAt) return 0
if(a.createdAt > b.createdAt) return -1
if(a.createdAt < b.createdAt) return 1
})
res.data.forEach((notebook:Notebook) => notebook.friendlyCreatedAt = friendlyDate(notebook.createdAt))
resolve(res)
}).catch(res => reject(res))
})
},