简介:
这节我们继续解析一个叫vue-property-decorator的第三方库,首先可以看它官网的一个介绍:
This library fully depends on [vue-class-component](https://github.com/vuejs/vue-class-component), so please read its README before using this library.
也就是说它是基于vue-class-component库的,在上一篇文章中我们介绍了如何在vue中利用装饰器使用类组件,我们写了一篇叫vue-class-component的文章,大家有兴趣可以去看一下。
实现:
创建工程:
我们直接copy一份上一节代码的demo,然后让它支持一下typescript
vue-property-decorator-demo
vue-property-decorator-demo
demo
index.html //页面入口文件
lib
main.js //webpack打包过后的文件
src
view
component.d.ts //类组件ts声明文件
component.js //类组件文件
demo-class.vue //demo组件
main.ts //应用入口文件
babel.config.js //babel配置文件
tsconfig.json //ts配置文件
package.json //项目清单文件
webpack.config.js //webpack配置文件
index.html:
我们直接引用打包过后的文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
<script src="http://127.0.0.1:8081/main.js"></script>
</body>
</html>
demo-class.vue:
<template>
<div @click="say()">{
{
msg}}</div>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "./component";
@Component
class DemoComponent extends Vue{
msg = 'hello world';
say(){
alert(this.msg);
}
}
export default DemoComponent;
</script>
main.ts:
加载demo.vue组件,挂在到“#app”元素上
import Vue from "vue";
import Demo from "./view/demo-class.vue";
new Vue({
render(h){
return h(Demo);
}
}).$mount("#app");
component.d.ts:
export declare const $internalHooks: string[];
export default function componentFactory(Component: any, options?: any): any;
component.js:
import Vue from "vue";
export const $internalHooks = [
'data',
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeDestroy',
'destroyed',
'beforeUpdate',
'updated',
'activated',
'deactivated',
'render',
'errorCaptured', // 2.5
'serverPrefetch' // 2.6
];
function collectDataFromConstructor(vm,Component) {
//创建一个组件实例
const data = new Component();
const plainData = {
};
//遍历当前对象的属性值
Object.keys(data).forEach(key => {
if (data[key] !== void 0) {
plainData[key] = data[key];
}
});
//返回属性值
return plainData
}
/**
* 组件工程函数
* @param Component //当前类组件
* @param options //参数
*/
function componentFactory(Component, options = {
}) {
options.name = options.name || Component.name; //如果options没有name属性的话就直接使用类名
//获取类的原型
const proto = Component.prototype;
//遍历原型上面的属性
Object.getOwnPropertyNames(proto).forEach((key) => {
// 过滤构造方法
if (key === 'constructor') {
return
}
// 赋值vue自带的一些方法
if ($interna

本文详细介绍了如何使用vue-property-decorator库在Vue中创建类组件,包括创建工程、运行工程、实现效果及代码实现。通过示例展示了如何在main.ts和组件中使用装饰器,并探讨了类组件的优缺点。
最低0.47元/天 解锁文章
5599

被折叠的 条评论
为什么被折叠?



