最近在学习
typescript
,并结合vue
练习一个demo.在这个demo将涉及如下知识点vue
- vue-class-component
- vuex-class
参考文章git
vue-cli
yarn global add @vue/cli
vue --version // @vue/cli 4.1.1
// 使用ui界面建立新项目, 固然也能够使用命令的方式 vue ui
这里要勾选typescript
github
等待安装.vuex
安装支持vuex
class模式的vuex-module-decorators
vue-cli
yarn add vuex-module-decorators
cd vue-typescript/src/views touch Counter.vue
添加如下内容(代码没法格式化,图片代替)/src/views/Counter.vue
typescript
修改/src/store/index.ts
学习
添加一个vuex-module
/src/store/counter.ts
ui
/src/store/index.ts
. 会看到,这个导出的store
中没有module
. 这是由于module
会在建立时动态导入.而后是添加了一个VuexModuleWithUpdater
, 这个类的用处是给全部的module
定义一个公共方法$updateState
, 而这个方法能够接受一个对象来更新module
中的state
, 其本质是一个mutation
./src/stroe/couter.ts
中, 定义了state
和module
的接口,这些接口将会在vue
组件中使用到.@Module({ name: 'counter', dynamic: true, store })
中的dynamic
表示这个module
将动态导入. store
则是导入的目标根据store
. 在导出这个module
时, 须要使用getModule
.最后来看页面组件(/src/views/Counter.vue
).spa
import CounterModule, { ICounter } from '@/store/modules/counter' class { get counterIns(): ICounter { return CounterModule } }
先导入关联的module
, 而后经过computed
属性将module
的实例挂载到当前的vue
组件中.这个counterIns
实例将包含全部的属性和方法(这与之前的vue注入state
和actions
的方式有所不一样).3d
在本demo主要涉及vue-property-decorator
和vuex-module-decorators
这两个库,能够让vue
和vuex
使用基于类的方式来编写. 日后将继续深刻学习.