vue-class-component 以class的模式写vue组件

原文链接:http://www.cnblogs.com/crazycode2/p/7821089.html

vue英文官网推荐了一个叫vue-class-component的包,可以以class的模式写vue组件。vue-class-component(以下简称Component)带来了很多便利:

1.methods,钩子都可以直接写作class的方法

2.computed属性可以直接通过get来获得

3.初始化data可以声明为class的属性

4.其他的都可以放到Component装饰器里

举个小例子

 

@Component({

props: {

  firstName: String,

  lastName: String

},

watch:{

},

computed:{//主要用来接收store

  ...mapState('spacName',['key1','key2','key3']),

 

   fullName() {

    return this.firstName + this.lastName;

  }

},

methods:{

},

mixins:[myMixins.js],

components: {

  'component-a': ComponentA

}

})

export class XXXX extends Vue {

firstName: string;

lastName: string;

 

//初始data

middleName = 'middle';

 

//computed 属性,这个也可以放在上面的修饰器写,上面不需要带get, 

get fullName() {

return this.firstName + this.lastName;

}

 

//method

hello() {

alert(`Hello ${this.fullName}!`);

}

 

//钩子

mounted() {

this.hello();

}

}

 

export interface xxx{ }

export interface yyy{ }

现在尽管可以以class的模式来写vue的组件了,但自动补全,代码提示等功能还是没有,要想获取好的代码提示还得是原语言啊,js代码在.ts,.js文件写,scss在.scss写,html在.html写。

最终vue组件以以下方式写感觉挺爽,很顺

 

import Vue from 'vue';

import Componet from 'vue-class-component';require('./XXX.template.scss');

 

@Component({

template: require('./XXX.template.html'),

props: {

firstName: String,

lastName: String

},

components: {

'component-a': ComponentA

}

})

export class XXXX extends Vue {

firstName: string;

lastName: string;

 

//初始data

middleName = 'middle';

 

//computed 属性

get fullName() {

return this.firstName + this.lastName;

}

 

//method

hello() {

alert(`Hello ${this.fullName}!`);

}

 

//钩子

mounted() {

this.hello();

}

}

现在各个文件回归它的本职工作了,哈哈哈,不过现在打包时有点小问题,

[Vue warn]: You are using the runtime-only build of Vue where the template option is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

解决方法也很简单,在webpack配置文件里 加上

 

alias: {

'vue': 'vue/dist/vue.esm.js'

}

即可。好的,现在代码补全,语法提示什么功能都回来了。

转载于:https://www.cnblogs.com/crazycode2/p/7821089.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值