vue2 + ts + vuex 构建脚手架 ( 实现一个 存储笔记功能 )

vue2 + ts + vuex 构建脚手架

创建项目

vue create vue2-ts-demo
暂时选择默认的!
npm i 安装依赖

安装ts
vue add @vue/typescript ( 一路 yes )
安装vuex
npm i vuex || vue add vuex
  • 关闭eslint 变量未使用的时候 报异常 package.json
  "eslintConfig": {
    "root": true,
    "rules": {
      "no-unused-vars":0
    }
  },

model 数据的类型 限制

model / ItemData.ts 文章的每一项数据的类型

// 笔记数组
import Category from './CateEnum'
class ItemData {
  id!: number
  categoryId!: Category
  title!: string
  content!: string
  createTime!: string

  // 构造函数 接受形参 => 赋值给 对应的变量
  constructor(
    id: number = -1,
    categoryId: Category = -1,
    title: string = '',
    content: string = ''
  ) {
    this.id = id
    // 需要使用 枚举类型 代表 文章
    this.categoryId = categoryId
    this.title = title
    this.content = content
    this.createTime = this.toSelfDateStr(Date.now())
  }

  // 毫秒时间戳 => 具体日期
  toSelfDateStr(
    timeSpan: number,
    sign: string = '-',
    timeSign: string = ':'
  ): string {
    // 将时间戳 转化未 日期对象
    const date = new Date(timeSpan)
    // 使用日期对象 getXXX方法 获取年月日等 再拼接
    let resDate = ''
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hours = date.getHours()
    const hours2 = hours < 10 ? '0' + hours : hours
    const minutes = date.getMinutes()
    const minutes2 = minutes < 10 ? '0' + minutes : minutes
    const seconds = date.getSeconds()
    const seconds2 = seconds < 10 ? '0' + seconds : seconds
    resDate =
      year +
      sign +
      month +
      sign +
      day +
      ' ' +
      hours2 +
      timeSign +
      minutes2 +
      timeSign +
      seconds2
    // 返回格式
    return resDate
  }
}

export default ItemData

model / CateEnum.ts 文章的类型 枚举

// 文章的枚举类型
// 0 工作; 1 生活; 2 学习
enum Category {
  Work = 0,
  Life = 1,
  Stydy = 2
}

export default Category;

main.ts 测试效果

import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false
import ItemData from './model/ItemData'
import Category from './model/CateEnum'

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

const item1 = new ItemData(1, Category.Stydy, '我是title', '学习vue2+ts')

console.log('item1', item1)
//item1 ItemData {id: 1, categoryId: 2, title: '我是title', content: '学习vue2+ts', createTime: '2022-7-27 13:20:22'}

测试 DateHelper 本地存储 与 ActionsHelper 笔记数组数据的转化

store / DateHelper.ts 存储类

// 存储类
class DateHelper{
  dataKey:string;
  privateKey:string;
  // privateKey:any;
  // 构造函数 接受 类调用时候 传递的参数
  constructor(dataKey:string,privateKey:string){
    this.dataKey =dataKey;
    this.privateKey = privateKey;
  }
  // 方法
  // 读取数据
  readData():any{
    // 1:读取 本地数据 ( 根据 dataKey 读取 )
    const strData:string |null = localStorage.getItem(this.dataKey);
    // 2:将 读取的 json数组 字符串 转化为数组对象
    let arrData:any = [];
    if ( strData != null ) {
      arrData = JSON.parse(strData)
    }
    // 3:返回 数组对象
    return arrData;
  }
  // 存储数据
  savaData(arrData:Array<Object>):void{
    // 1: 将数组 转化为 json字符串
    const str:string = JSON.stringify(arrData);
    // 2:将字符串 保存到 本地 localStorage 中
    localStorage.setItem(this.dataKey,str)
  }
  // 新增数据
  addData(conStr:string):number{
    // 1:读取本地 现有数据
    const arr:any = this.readData();
    // 2:创建一个 新的评论对象 并且设置 评论内容属性 {  content: '菜鸡' }
    interface locObject {
      [key: string]: any
    }
    const obj:locObject = {
      content:conStr,
    }
    // 3.1: 自动 生成一个主键值 (id值) {  content: '菜鸡' ,id:1 }
    const newId:any = arr.length > 0 ? arr[arr.length - 1][this.privateKey] + 1: 1;
    obj[this.privateKey] = newId;
    // 4将 添加 主键值 的对象 添加到数组
    arr.push(obj)
    // 5:将数组 保存 到 localStorage 中
    this.savaData(arr)
    // 6:返回 id
    return newId;
  }
  // 删除 id 
  removeDataById(id:string | number):boolean{
    //1: 读取 本地数组
    const arr = this.readData()
    //2: 查找要删除的 评论对象 下标 并且保存到本地
    interface locObject {
      [key: string]: any
    }
    const index = arr.findIndex( (ele:locObject) => {
      return ele[this.privateKey] == id;
    })
    
    // 如骨 下标 大于 -1 代表着可以找到 需要删除的数据
    if ( index > -1) {
      arr.splice(index,1);
      // 保存到本地
      this.savaData(arr)
      return true;
    }
    return false; // 否者 返回 false
  }
}
// 调用类

export default DateHelper

store / ActionsHelper.ts 业务处理类 ( 新增笔记、修改笔记、删除笔记)

// 业务处理相关
import DateHelper from './DateHelper'
import ItemData from '@/model/ItemData'
class ActionsHelper {
  // 1:负责数据处理
  dataHelper: DateHelper = new DateHelper('menoData', 'id')
  // 1.1 笔记数组
  menoList!: Array<ItemData>
  // 2:负责业务处理
  constructor() {
    // 读取本地数据,将笔记数组 保存到 this.menoList变量之中
    this.menoList = this.readonly()
  }

  // 功能1:读取笔记
  readonly(): Array<ItemData> {
    // 1:读取 本地的 Object数组 - dataHelper方法调用
    const arrObj = this.dataHelper.readData()

    // 2:将 Object数组 转成 ItemData数组
    const arrItem = arrObj.map((ele: any) => {
      const item: ItemData = new ItemData() // 把变量的对象 转化为  ItemData类型的数组 ( 返回arrItem)
      item.id = ele.id
      item.categoryId = ele.categoryId
      item.title = ele.title
      item.content = ele.content
      item.createTime = ele.createTime
      return item
    })
    return arrItem
  }
  // 功能2:新增笔记
  add(item: ItemData): number {
    // 2.1:保存笔记到本地
    item.id = this.dataHelper.addData(item.content) // ???
    // 2.2:修改 menoList 笔记数据
    this.menoList.push(item)
    // 2.3:把新增后的笔记数据 保存到本地
    this.dataHelper.savaData(this.menoList)
    return -1
  }

  // 功能3:修改笔记
  edit(item: ItemData): void {
    // 3.1 找出 数组众 id 相同的对象
    const eleItem: ItemData | undefined = this.menoList.find((ele: any) => {
      return ele.id === item.id
    })
    // 3.2 修改 对象的值 将传入的对象 item各个属性的值 覆盖设置 给数组之中找到的对象属性
    if (eleItem) {
      eleItem.categoryId = item.categoryId
      eleItem.title = item.title
      eleItem.content = item.content
      // 3.3 更新后的数组 保存到本地
      this.dataHelper.savaData(this.menoList)
    }
  }

  // 功能4:删除笔记
  remove(id: number): void {
    // 4.1:根据id 找出 要删除的 对象 再数组中的 下标
    const index: number = this.menoList.findIndex((ele: any) => {
      return ele.id === id
    })
    // 4.2 根据下标 调用数组 .splice 方法来删除对象
    if (index > -1) {
      this.menoList.splice(index, 1)
      // 4.3 把删除对象删除后 数组重新保存会 本地
      this.dataHelper.savaData(this.menoList)
    }
  }
}

export default ActionsHelper

测试 使用 上面两个类 main.ts ( 新增笔记、修改笔记、删除笔记)

import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false
import ItemData from './model/ItemData'
import Category from './model/CateEnum'
import ActionsHelper from './store/ActionsHelper'
// import DateHelper from './store/DateHelper'

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

// const item1 = new ItemData(-1, Category.Stydy, '我是title3', '学习vue2+ts-3') 
// const dateHelper = new DateHelper('menoData', 'id')
// dateHelper.savaData([item1]) // 假如本地没有数据的时候 测试一下存储!
// console.log('item1', item1) // {id: -1, categoryId: 2, title: '我是title3', content: '学习vue2+ts-3', createTime: '2022-7-27 15:09:58'}


const ah = new ActionsHelper()

// const item1 = new ItemData(-1, Category.Stydy, '我是title3', '学习vue2+ts-3') 
// 测试 新增功能
// ah.add(item1) // 注意点:新增的对象 id必须为-1 或者为""

// const item2 = new ItemData(2, Category.Stydy, '我是title2-2', '学习vue2+ts-2-2') 
// // 测试 修改功能
// ah.edit(item2) // 注意点:新增的对象 id必须为-1 或者为""

// 测试 删除功能
// ah.remove(4)

console.log('ah', ah.menoList)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值