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 }, 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(); } }
現在盡管可以以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' }
即可。好的,現在代碼補全,語法提示什么功能都回來了。