model.js

将数据操作封装进model.js

  1. const localStorageItemName = 'recordList'
  2. const model = {
  3. fetch(){
  4. return JSON.parse(window.localStorage.getItem(localStorageItemName) || '[]')
  5. },
  6. save(data){
  7. window.localStorage.setItem(localStorageItemName, JSON.stringify(data))
  8. }
  9. }
  10. export default model

money组件import model.js
image.png
发现在ts中无法用import引入js文件
改用require

  1. const model = require('@/model.js').default

不想要default, model.js改用具名导出

  1. export {model}
  1. const model = require('@/model.js').model
  2. // 或者
  3. const {model} = require('@/model.js')

model.ts

将类型声明放在xxx.d.ts文件内,ts能识别为全局类型
可以不需要用export

  1. // 不要用Record,是保留字
  2. type RecordItem = {
  3. tags: string[],
  4. notes: string,
  5. type: string,
  6. amount: number,
  7. createAt?: Date
  8. }

但是如果不用export,在vue文件里会有红色波浪线,所以还是用export

  1. export type RecordItem = {
  2. -- snip --
  3. }
  1. import {RecordItem} from '@/custom';
  2. // 如果只导入类型,可以加上type
  3. import type {RecordItem} from '@/custom';

model.ts

  1. const localStorageItemName = 'recordList';
  2. const model = {
  3. fetch() {
  4. return JSON.parse(window.localStorage.getItem(localStorageItemName) || '[]') as RecordItem[];
  5. },
  6. save(data: RecordItem[]) {
  7. window.localStorage.setItem(localStorageItemName, JSON.stringify(data));
  8. }
  9. };
  10. export default model;

fetch里用as指定了返回值的类型, 所以在声明recordList时就不需要再指定一遍类型了
image.png
把深拷贝方法也放进model.ts里

  1. const localStorageItemName = 'recordList';
  2. const model = {
  3. clone(data: RecordItem[] | RecordItem){
  4. return JSON.parse(JSON.stringify(data))
  5. },
  6. -- snip --
  7. };
  8. export default model;