model.js
将数据操作封装进model.js
const localStorageItemName = 'recordList'
const model = {
fetch(){
return JSON.parse(window.localStorage.getItem(localStorageItemName) || '[]')
},
save(data){
window.localStorage.setItem(localStorageItemName, JSON.stringify(data))
}
}
export default model
money组件import model.js
发现在ts中无法用import引入js文件
改用require
const model = require('@/model.js').default
不想要default, model.js改用具名导出
export {model}
const model = require('@/model.js').model
// 或者
const {model} = require('@/model.js')
model.ts
将类型声明放在xxx.d.ts文件内,ts能识别为全局类型
可以不需要用export
// 不要用Record,是保留字
type RecordItem = {
tags: string[],
notes: string,
type: string,
amount: number,
createAt?: Date
}
但是如果不用export,在vue文件里会有红色波浪线,所以还是用export
export type RecordItem = {
-- snip --
}
import {RecordItem} from '@/custom';
// 如果只导入类型,可以加上type
import type {RecordItem} from '@/custom';
model.ts
const localStorageItemName = 'recordList';
const model = {
fetch() {
return JSON.parse(window.localStorage.getItem(localStorageItemName) || '[]') as RecordItem[];
},
save(data: RecordItem[]) {
window.localStorage.setItem(localStorageItemName, JSON.stringify(data));
}
};
export default model;
fetch里用as指定了返回值的类型, 所以在声明recordList时就不需要再指定一遍类型了
把深拷贝方法也放进model.ts里
const localStorageItemName = 'recordList';
const model = {
clone(data: RecordItem[] | RecordItem){
return JSON.parse(JSON.stringify(data))
},
-- snip --
};
export default model;