vue+TypeScript+Element实现后台管理系统及采坑记

1,029 阅读2分钟

项目预览

项目预览地址

详情可看github源码,地址:github.com/zouzhibin/t…

项目介绍

.如下图所示 这是一个用vue-cli3 基于Typescript实现的后台管理系统

功能

已完成的

  • 首页引入echarts 图标插件
  • 实现外链
  • 菜单栏的递归
  • 表格组件的展示
  • 表单组件的展示
  • 进度条的展示
  • 轮播图的展示
  • JSON 编辑器的展示
  • vuex的引入结合使用

待优化或者实现

  • 更多Typescript的优化技巧

前端主要技术

  • typescript 3.9.3
  • vue 2.6.11
  • webpack 4.44.1
  • vue-cli3
  • vuex 3.4.0
  • vuex-class 0.3.2
  • element-ui 2.13.2
  • vue-router 3.2.0
  • axios 0.19.2
  • echarts 4.8.0

项目目录介绍

│  App.vue
│  main.ts 主文件入口
│  shims-tsx.d.ts 声明文件
│  shims-vue.d.ts
├─assets
├─components 组件集成
├─router 路由模块 分为静态路由和动态路由
├─store vuex 模块
├─types ts类型声明文件 有些第三方库没有提供第三方ts声明 需要自己写
│      global.d.ts
├─utils 工具方法
└─views 页面部分

首先来说遇到的坑

.vue文件中使用typescript

npm install vue-class-component -S
npm install vue-property-decorator -S

写法如下图

在 script 标签上添加lang="ts" 代表你要用语法进行代码的校验

可以看到如上图引入了关键的 vue-property-decorator 它暴露了出来一些方法

简单介绍下vue-property-decorator这个组件完全依赖于vue-class-component.它具备以下几个属性:

  • @Component (完全继承于vue-class-component)
  • @Emit
  • @Inject
  • @Provice
  • @Prop
  • @Watch
  • @Model
  • Mixins (在vue-class-component中定义);

ts文件中如何使用vuex

npm install vuex-class -S

vuex在ts文件中的使用主要是利用vuex-class

import Vue from 'vue'
import Component from 'vue-class-component'
import {
  State,
  Getter,
  Action,
  Mutation,
  namespace
} from 'vuex-class'

const someModule = namespace('path/to/module')

@Component
export class MyComp extends Vue {
  @State('foo') stateFoo
  @State(state => state.bar) stateBar
  @Getter('foo') getterFoo
  @Action('foo') actionFoo
  @Mutation('foo') mutationFoo
  @someModule.Getter('foo') moduleGetterFoo

  // If the argument is omitted, use the property name
  // for each state/getter/action/mutation type
  @State foo
  @Getter bar
  @Action baz
  @Mutation qux

  created () {
    this.stateFoo // -> store.state.foo
    this.stateBar // -> store.state.bar
    this.getterFoo // -> store.getters.foo
    this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
    this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
    this.moduleGetterFoo // -> store.getters['path/to/module/foo']
  }
}

踩坑

  • Could not find a declaration file for module 'vue-count-to' 可以进行ts声明添加
declare module 'vue-count-to';
  • Property 'validate' does not exist on type 'Vue | Element | Vue[] | Element[]'.   Property 'validate' does not exist on type 'Vue'.
import { Form as ElForm } from "element-ui";
<ElForm>this.$refs["accountfrompwd"];

或者 (this.$refs.loginForm as HTMLFormElement).validate