model.js
将数据操作封装到model.js
const localStorageName = 'records'
const model = {
fetch(){
return JSON.parse(window.localStorage.getItem(localStorageName) || '[]')
},
save(data){
window.localStorage.setItem(localStorageName, JSON.stringify(data));
}
}
export default model
在TS中import JS文件报错
改用require
const model = require('@/model.js');
但是这样读不到model里面的函数,是因为引入的是default对象
所以要改成
const model = require('@/model.js').default;
也可以将default导出改成命名导出
export {model}
导入时
const {model} = require('@/model.js');
将JS改成TS
声明全局类型
在src根目录新建custom.d.ts文件(只需要以d.ts结尾),d代表declaration
// Record是关键字,不能使用
type RecordItem = {
tags: string[];
type: string;
notes: string;
amount: number;
createTime: Date;
}
修改model.ts
const localStorageName = 'records';
const model = {
fetch() {
return JSON.parse(window.localStorage.getItem(localStorageName) || '[]') as RecordItem[];
},
save(data: RecordItem[]) {
window.localStorage.setItem(localStorageName, JSON.stringify(data));
},
clone(data: RecordItem[] | RecordItem){
return JSON.parse(JSON.stringify(data));
}
};
export default model;
改用import引入
import model from '@/model';