关于vue-class-component和vue-property-decorator的使用
tip: vue-property-decorator 依赖于 vue-class-component(vue-property-decorator 是在 vue-class-component的基础上进行扩展,所以vue-class-component有的vue-property-decorator也有,使用时可以只导入vue-property-decorator,但安装包时两个包都需要下载)
-
基础写法
import { Vue, Component, Prop, PropSync } from 'vue-property-decorator' @Component export default class HelloWorld extends Vue{ // a. 声明变量 // 注意:当变量的初始值为undefined时,它不是响应式的 // 解决办法: // 1. 赋值为null // 2. 使用data的钩子函数 data(){ return { hello: undefined } } message = 'hello world' // b. 声明函数 hello() { console.log('Hello World!') } // c. 计算属性 // 注意:computed对象中有 cache属性,设置为false表示不缓存(即每次取数据都重新执行一遍函数),默认为true(即只有当相关数据改变,才会重新执行函数) get name(){ return this.firstName + ' ' + this.lastName } set name(){ const splitted = value.split(' ') this.firstName = splitted[0] this.lastName = splitted[1] || '' } // d. Hooks mounted(){ } // c. // 其他选项写在 @Component({})中 }
-
注册除了生命周期以外的钩子函数
// 注册钩子函数(推荐新建register.ts文件,在main.js中引入 --> 组件定义前引入) import Component from 'vue-class-component' Component.registerHooks([ 'beforeRouteEnter', 'beforeRouteLeave', 'beforeRouteUpdate' ]) // 注册完之后就可以在组件类中直接使用(与生命周期钩子函数相同)
-
自定义装饰器
import { createDecorator } from "vue-class-component"; export const Log = createDecorator((options, key) => { const originalMethod = (options.methods as any)[key]; // 得到装饰器装饰的方法 // 包装原方法 (options.methods as any)[key] = function wrapperMethod(...args: any) { console.log(`Invoked: ${ key}(`, ...args, ")"); // Invoke the original method. originalMethod.apply(this, args); }; }); // 自定义组件中使用 // 绑定事件:<button @click="hello($event,2,3,4)">hello</button> // 调用hello方法 @Log hello(e: any, value: string) { console.log('hello'); }
-
extend
组件的扩展 --> 继承父组件(extends) --> 可以使用父组件的变量// super.js 父组件 import Vue from 'vue' import Component from 'vue-class-component' @Component export default class Super extends Vue { superValue = 'Hello' } // 子组件 import Super from './super' import Component from 'vue-class-component' @Component export default class HelloWorld extends Super { created() { console.log(this.superValue) // -> Hello 可以直接通过this访问父组件的变量(相当于直接继承了父组件的所有script内容) } }
-
mixins
// 新建mixins文件存放 // mixins.ts import Vue from 'vue' import { Component } from 'vue-property-decorator' @Component export class Hello extends Vue { hello = 'Hello' } @Component export class World extends Vue { world = 'World' } // 在组件中使用 import { Component, mixins } from 'vue-property-decorator' import { Hello, World } from './mixins' // `mixins` can receive any number of arguments. @Component export class HelloWorld extends mixins(Hello, World) { created () { console.log(this.hello + ' ' + this.world + '!') // -> Hello World! } }
-
注意事项:
a. 在类形式的组件中,this只是Vue实例的代理对象(this指向Vue实例)
b. 不能使用箭头函数去定义方法(this在箭头函数中指向undefined) -
显示赋值断言 “!”
前提情节: ts2.7引入了一个新的flag:–strictPropertyInitialization。这个flag检查并确保一个类在初始化时,每一个属性都必须在构造器内初始化,或者在属性定义时赋予初始值class C { foo: number