项目起步:
安装vue-proporty-decorator,之后scipt的标签会变为lang="ts"
npm i -D vue-proporty-decorator
⭐export default class "组件名" extends Vue此后所有的配置都在里面写,但是extends的内容并不是固定的,并且只能单一继承
全新(划掉)的知识
@Component
类装饰器–应用于类构造函数,其参数是类的构造函数 @Component就是个类装饰器,作用于Vue对象
语法: @Component(options) 说明: options 中需要配置 decorator 库不支持的属性, 如: components, filters, directives等
📍其他的东西都可以写在类里面,比如@Ref,@Watch,@Emit
data
对于data里的变量类型,我们可以直接按ts定义类变量的写法写就可以
ValA: string = 'hello world';
ValB: number = 1;
但是注意在此之前要修改一下自动判断类型的配置,否则会编译报错
//修改.eslintrc文件
"@typescript-eslint/no-inferrable-types": "off" ,// 关闭类型推断,
'no-mixed-spaces-and-tabs':0
同时也可以关闭eslint类型检查,文件是vue.config.jslintOnSave:false
computed
对于Vue中的计算属性,我们只需要将该计算属性名定义为一个函数,并在函数前加上get关键字即可.原本Vue中的computed里的每个计算属性都变成了在前缀添加get的函数
import {Vue, Component} from 'vue-property-decorator';
@Component
export default class "组件名" extends Vue{
get ValA(){
return 1;
}
}
相当于:
computed: {
ValA: function() {
return 1;
}
}
@Prop
属性参数:@Prop(options: (PropOptions | Constructor[] | Constructor) = {})
参数说明:@Prop装饰器接收一个参数,这个参数可以有三种写法: PropOptions比较常用,包含以下选项:type(类型), required(必填), default(默认值), validator(验证函数) Constructor[],指定 prop 的可选类型; Constructor,例如String,Number,Boolean等,指定 prop 的类型
📍注意:属性的ts类型后面需要加上undefined类型;或者在属性名后面加上!,表示非null 和 非undefined的断言,告诉TypeScript我这里一定有值,否则编译器会给出错误提示
@Prop接受的类型比如Number是JavaScript的类型,之后定义的属性类型number则是TypeScript的类型.
//@Prop(js类型,首字母大写)参数名 +非空断言:ts类型
import {Vue, Component, Prop} from 'vue-property-decorator';
@Prop(Number) propA!: number;
父组件用v-bind绑定
子组件用@prop接收
@PropSync
属性参数:@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})
@PropSync装饰器与@prop用法类似,二者的区别在于:
@PropSync 装饰器接收两个参数: propName: string 表示父组件传递过来的属性名; options: Constructor | Constructor[] | PropOptions 与@Prop的第一个参数一致; @PropSync 会生成一个新的计算属性。
📍注意:使用PropSync的时候是要在父组件配合.sync使用的
//父组件
<PropSyncComponent :like.sync="like"></PropSyncComponent>
import PropSyncComponent from '@/components/PropSyncComponent.vue';
@Component({components: { PropSyncComponent },})
//子组件
<h2>syncedlike:{{ syncedlike }}</h2>
import { Component, Prop, Vue, PropSync,} from 'vue-property-decorator';
//@PropSync('父组件传递的参数名',{type:类型}) 子组件期望的名字+非空断言+类型判断
@PropSync('like', { type: String }) syncedlike!: string;
@Watch
属性参数:@Watch(path: string, options: WatchOptions = {})
参数说明:@Watch 装饰器接收两个参数:
path: string 被侦听的属性名; options?: WatchOptions={} options可以包含两个属性 : immediate?:boolean 侦听开始之后是否立即调用该回调函数; deep?:boolean 被侦听的对象的属性被改变时,是否调用该回调函数; 在普通vue项目中使用watch
watch: {
// 这种写法默认 `immediate`和`deep`为`false`
'child': this.onChangeValue,
'person': {
handler: 'onChangeValue',
immediate: true,
deep: true
}
},
装饰器改造:@watch(被监听的属性名)下接onChangeValue方法
import {Vue, Component, Watch} from 'vue-property-decorator';
@Watch('child')
onChangeValue(newVal: string, oldVal: string){
// todo...
}
@Watch('person', {immediate: true, deep: true})
onChangeValue(newVal: Person, oldVal: Person){
// todo...
}
@Ref
属性参数:@Ref(refKey?: string)
参数说明:@Ref 装饰器接收一个可选参数,用来指向元素或子组件的引用信息。如果没有提供这个参数,会使用装饰器后面的属性名充当参数
自己获取自己的元素信息:
<button @click="getRef()" ref="aButton">获取ref</button>
import { Vue, Component, Ref } from 'vue-property-decorator';
export default class RefPage extends Vue {
@Ref('aButton') readonly ref!: HTMLButtonElement;
}
获取子组件的信息:
<RefComponent name="names" ref="RefComponent"></RefComponent>
@Ref('RefComponent') readonly RefC!: HTMLDocument;
@Emit
this.$emit 算是父子通信的一种方法,作用为在子组件可以触发父级函数并且可以传参
属性参数:@Emit(event?: string) 参数说明:
@Emit 装饰器接收一个可选参数,充当事件名。 @Emit的回调函数的参数,会在回调函数没有返回值的情况下,被emit会在Promise对象被标记为resolved之后触发;
www.duanlonglong.com/qdjy/1241.h…
子组件给父组件通过emit传参的写法:
//子组件
<button @click="emitTodo">点击我</button>
//写在@Emit('test')此时test这个值和this.$emit('test')要触发的是一致的
@Emit('test')
emitTodo(n: string) {
//这里是要传递的值
return 'a';
}
//父组件
<Test @test="getMyEvent"></Test>
getMyEvent(msg:string){
console.log('子组件传来的值',msg)
}
@Inject
属性参数:
@Provide(key?: string | symbol)
参数说明:
-
提供/注入装饰器,
-
key可以为string或者symbol类型,
-
相同点:Provide/ProvideReactive提供的数据,在内部组件使用Inject/InjectReactive都可取到
不同点:
-
如果提供(ProvideReactive)的值被父组件修改,则子组件可以使用InjectReactive捕获此修改
最外层组件:
import {
Vue, Component, Provide, ProvideReactive,
} from 'vue-property-decorator';
import provideGrandpa from '@/components/ProvideGParentComponent.vue';
@Component({
components: { provideGrandpa },
})
export default class ProvideInjectPage extends Vue {
@Provide('foo') foo = 'foo'
@ProvideReactive('reactiveKey1') reactiveKey1 = 'reactiveKey1'
@ProvideReactive('reactiveKey2') reactiveKey2 = 'reactiveKey2'
created() {
// 此处验证@Provide @ProvideReactive 键值被修改
this.foo = 'foo111'
this.reactiveKey1 = 'reactiveKey111'
this.reactiveKey2 = 'reactiveKey222'
}
}
接下来每一层都套一个组件,最后的孙子组件代码如下:
<template>
<div class="hello">
<h3>孙子的组件</h3>
爷爷组件里面的foo:{{ foo }}<br />
爷爷组件里面的fooReactiveKey1:{{ reactiveKey1 }}<br />
爷爷组件里面的fooReactiveKey2:{{ reactiveKey2 }}
</div>
</template>
<script lang="ts">
import {
Component, Vue, Inject, InjectReactive,
} from 'vue-property-decorator';
@Component
export default class ProvideSonComponent extends Vue {
@Inject('foo') foo!: string
@InjectReactive('reactiveKey1') reactiveKey1!: string
@InjectReactive('reactiveKey2') reactiveKey2!: string
}
</script>
📍展示的结果说明如果提供@provide的值被父组件修改,子组件是无法捕捉的
vuex-module-decorators
安装:npm install vuex-module-decorators
// store/modules/passenger.ts
import {Module,VuexModule,Mutation,Action,getModule,} from 'vuex-module-decorators';
import store from '@/store';
//声明接口类型
type User = { username: string; password: string; }
// dynamic: true: 动态创建动态模块,即new Vuex.Store({})里面不用注册的.空着就行,
// store,当前模块注册到store上.也可以写在getModule上,即getModule(PassengerStore,store)
// namespaced: true, name: 'passenger' 命名空间
@Module({
name: 'passenger', dynamic: true, namespaced: true, store,
})
export default class PassengerStore extends VuexModule {
// state => 要public不然外面调用不到
public loginInfo: User[] = [];
// getter
get userNumber(): number {
return this.loginInfo.length;
}
@Mutation
USERINFO(user: User): void {
console.log(user);
this.loginInfo.push(user);
}
// commit的两种调用方式,第一种,Action后面的括号里面添加commit,然后return的结果就是USERINFO的参数
@Action({ commit: 'USERINFO' })
getZhangsan(): User {
return { username: '张三', password: 'zhangsan' };
}
// 第二种,直接this.USERINFO调用;
@Action
getLisi(): void {
const user = { username: '李四', password: 'lisi' };
this.context.commit('USERINFO', user); // commit调用
// this.USERINFO(user); // 直接调用
}
}
// 使用getModule: 对类型安全的访问
export const PassengerStoreModule = getModule(PassengerStore);
代码分析:
//可以看出,声明state的话就像在vue文件里面声明data一样,直接写明即可
@Module
export default class Vehicle extends VuexModule {
wheels = 2
}
等同于下面的代码
export default {
state: { wheels: 2 }
}
//如果是getter的话,那么就在data下面用get方法,函数名任意取,要有返回值
@Module
export default class Vehicle extends VuexModule {
wheels = 2
get axles() {
return this.wheels / 2
}
}
等同于下面的代码
export default {
state: { wheels: 2 },
getters: {
axles: (state) => state.wheels / 2
}
}
//Mutation中其实就是写方法,但是和前两个不同的是他要在前面加上@,然后照常声明函数
@Module
export default class Vehicle extends VuexModule {
wheels = 2
@Mutation
puncture(n: number) {
this.wheels = this.wheels - n
}
}
等同于下面的代码
export default {
state: { wheels: 2 },
mutations: {
puncture: (state, payload) => {
state.wheels = state.wheels - payload
}
}
}
@Actions
这个相对于前面的较为特殊,他有两种方法去调用mutation的方法
第一种:Action后面的括号里面添加commit,然后return的结果就是mutation方法调用得到的参数
@Action({ commit: 'USERINFO' })后面加上方法,后期组件通过store+方法去调用
第二种:直接this.USERINFO调用;
getLisi(): void {
const user = { username: '李四', password: 'lisi' };
this.context.commit('USERINFO', user); // commit调用
// this.USERINFO(user); // 直接调用
}
也就是写在函数方法里面,this.context.commit(mutation方法名,要传递的参数)