vue开发小想法

这周入职新公司,公司这边用vue框架,我习惯使用typescript来写东西,vue搞出了.vue文件,连js都不算,在.vue文件中ts/js的代码提示,补全都没有了,对于我这样有小偏执的人来讲,不能接受。javascript

vue英文官网推荐了一个叫vue-class-component的包,能够以class的模式写vue组件。vue-class-component(如下简称Component)带来了不少便利:css

  1. methods,钩子均可以直接写做class的方法html

  2. computed属性能够直接经过get来得到vue

  3. 初始化data能够声明为class的属性java

  4. 其余的均可以放到Component装饰器里
    举个小例子webpack

@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的组件了,但自动补全,代码提示等功能仍是没有,至少我用的vscode没有这个功能,跑个题先,vscode真的很是棒,不愧是微软出品,写typescript超级赞,加上jsconfig.json写javascript也很不错,vscode出来以前我都是用sublime text,vscode不断出新功能,sublime就替补了。话归正题,要想获取好的代码提示还得是原语言啊,js代码在.ts,.js文件写,scss在.scss写,html在.html写web

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

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();
    }
}

如今各个文件回归它的本职工做了,哈哈哈,不过如今打包时有点小问题,npm

[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配置文件里 加上json

alias: {
    'vue': 'vue/dist/vue.esm.js'
}

便可。好的,如今代码补全,语法提示什么功能都回来了

不使用typescript,也能够写javascript,经过babel来编译也是能够的

相关文章
相关标签/搜索