在vue项目中使用TS
1. 将vue项目注入ts 引入和使用
webpack的打包配置:vue-cli webnpack 编译时
entry 入口 设置
entry: {
app: './src/maikn.ts'
}
2. resolve: extensions 添加 ts 用于处理尝试的数据尾缀列表
- 问: 如何在webpack新增处理类型文件: resolve配置项的extension里添加ts文件
TS 配置文件: typeScript.ts
vue/vuex + ts
1. 定义组件的方式上: 形式上:
import vue from 'vue'
const Compoinent = Vue.extend({
// 类型
})
2. 注入实例: 使用官方工具:vue-class-component
- 相当于给vue 添加了一个类装饰器的能力 从而实现实例 的注入
import Component from 'vue-class-component'
export default class myComponent extends Vue {
message: string = 'hello'
onClick(): void {
console.log(this.message)
}
}
3. 独立模块的声明: 利用 ts的额外补充模块 declare实现 使之可以被独立引用
declare module '*.vue' {
import Vue from 'vue'
export default vue
}
declare module 'typings/vuePlugin.d.ts'{
interface Vue {
myProps: string
}
}
// 实例中使用
let vm = new Vue()
console.log(vm.myProps)
4. props = 提供propType原地声明联合变量
import { propType } from 'vue'
interface customPayload {
str: string,
number: number,
name: string
}
const Component = Vue.extend({
pros: {
name: String,
success: {
type: String
},
payLoad: {
type: Object as propType<customPayload>
},
callback: {
type: Function as propType<() => void>
}
}
})
5. computed 和 methods
computed: {
getMsg():string {
return this.click() + '!'
}
},
methods: {
click(): string {
return this.message + 'zhaowa'
}
}
6. vuex的接入 - 声明使用
// vuex.d.ts声明模块 - ComponentCustomProperties
declare module '@vue/runtime-core' {
interface State {
count: number
}
interface ComponemtCustomProperties {
$store: Store<State>
}
}
7. api形式编码实现
// store.ts - 状态机侧
import { InjectionKey } from 'vue'
import {
createStore,
Store
} from 'vuex'
export interface State {
count: number;
}
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
state: {
count: 0
}
})
// main.ts - 入口侧代码
import { createApp } from 'vue'
import { store, key } form './store'
const app = createApp({
// 参数
})
// 利用了provide。inject
app.use(store, key)
// => 传入injectionkey
app.mount('#app')
// 消费方
import { useStore } from 'vuex'
import { key } from './store'
export default {
const store = useStore(key)
// store.state.count
}
8. vuex面向对象 (装饰器 结构更加统一) - 使用vuex-class 工具
import { State. Action, Getter } from "vuex-class"
export defaulty class App extends Vue {
// 利用属性装饰器整合store的状态
@store login: boolean
// 利用事件装饰器整合store方法
@Action setInit: ()=> void
get isLogin: boolean
mounted() {
this.setInit()
this.isLogin = this.login
}
}