如何在vue中使用ts开发

用了这么久的vue,终于踏出第一步使用ts去开发,发现真的是一时用ts一时爽,一直用ts一直爽。因此今天大概说一下怎么用ts简单开发。javascript

1.首先,更改一下webpack配置css

  1. 修改入口文件 [由于使用ts开发,因此文件都是ts]

    entry: {
        app: '.src/main.js'
    }复制代码

  2. 根路径下添加 tsconfiog.js配置文件,下面的是本身的一份简单的配置可参考

    {
      // 编译选项 "compilerOptions": { "module": "esnext", "strict": true, "jsx": "preserve", "typeRoots" : ["./typings"], "importHelpers": true, "moduleResolution": "node", "experimentalDecorators": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "sourceMap": true, "baseUrl": ".", "skipLibCheck": true, "skipDefaultLibCheck": true, "strictNullChecks": true, "downlevelIteration": true, "target": "es5", "noImplicitAny": false, "allowJs": true, "outDir": "./dist/", // 输出目录 "noImplicitThis": false, "removeComments": false, "types": [ "webpack-env" ], "paths": { // @表明src模块的路径 "@/*": [ "src/*" ] }, "lib": [ // 编译过程当中须要引入的文件 "esnext", "dom", "dom.iterable", "scripthost", "es5", "es2015", "es2016", "es2017", "es2015.promise", "es2015.collection", "es2015.iterable", "es2015.core", "dom" ] }, "awesomeTypescriptLoaderOptions": {}, "declaration": true, "include": [ "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", ], "exclude": [ "node_modules", "src/main.ts" ]}复制代码

  3. 根目录下添加 tslint.json文件 ,[规范一下书写ts],下面的也是一些简单配置

    {    "extends": [        "tslint:recommended"    ],    "lib": [        "ES2015",        "ES2016",        "ES2017"    ],    "linterOptions": {        "exclude": [            "node_modules",            "dist",            "config",            "build",            "./**/*.js",            "src/api/**",            "src/components/common/**",            "src/components/page/**",            "src/components/public/**",            "static/**"        ]    },    "rules": {        "member-access": [            true,            "no-public"        ],        "interface-name": [            true,            "always-prefix"        ],        "align": [            true,            "parameters",            "statements"        ],        "class-name": true,        "comment-format": [            true,            "check-space"        ],        "curly": true,        "eofline": true,        "forin": false,        "indent": [            true,            "spaces"        ],        "noImplicitThis": false,        "jsdoc-format": false,        "label-position": true,        "max-line-length": [            true,            200        ],        "no-any": false,        "no-arg": true,        "no-bitwise": false,        "no-conditional-assignment": true,        "no-consecutive-blank-lines": true,        "no-console": [            false,            "debug",            "info",            "log",            "time",            "timeEnd",            "warn",            "trace"        ],        "no-construct": true,        "no-constructor-vars": false,        "no-debugger": false,        "no-duplicate-variable": true,        "no-empty": false,        "no-eval": true,        "no-internal-module": true,        "no-namespace": true,        "no-reference": true,        "no-shadowed-variable": false,        "no-string-literal": true,        "no-switch-case-fall-through": false,        "no-trailing-whitespace": true,        "no-unused-expression": [            true,            "allow-fast-null-checks"        ],        "no-use-before-declare": false,        "no-var-keyword": true,        "no-var-requires": false,        "object-literal-sort-keys": false,        "one-variable-per-declaration": [            true,            "ignore-for-loop"        ],        "quotemark": [            true,            "single",            "jsx-double"        ],        }复制代码

  4. 要让ts认识vue文件,[在src路径下面添加vue-shim-d.ts]

    import router from '@/config/router';
    import { Comfirm, MessageBox } from 'element-ui';
    import Vue from 'vue';import VueRouter from 'vue-router';
    import { Route } from 'vue-router';import Tools from '@/utils/tools';
    import Api from '@/config/api';
    // 扩充
    declare module 'vue/types/vue' {
      // 这些是全局属性,能够直接this.$api这样相似使用 
      interface Vue {    
        $router: VueRouter;        
        $route: Route;          
        $message: MessageBox;        
        $conform: Comfirm;        
        $tools: Tools;        
        $api: Api;     
    }}复制代码

须要注意一点的是在导入vue文件的时候,要写上.vue后缀,由于TypeScript默认识别ts文件。vue

2. 改造一下vue文件java

在这以前咱们须要安装一个插件 vue-property-decorator,是在 vue-class-component 上加强了更多的结合 Vue 特性的装饰器,新增了一些装饰器。

src/app.vuenode

 [lang="ts",让webpack把这段代码识别为ts,除了须要改造一下script标签内的内容,其余地方都无需修改]webpack

<template>  
    <div id="app">    
        <router-view></router-view>  
    </div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';
    @Componentexport 
    default class App extends Vue {  
        private created() {    
            // 不须要保持当前路由,则前往首页    
            if (!location.hash.includes('keepRoute=true')) {      
                this.$router.push({ path: '/' });    
            }  
         }}
</script>

<style>
@import "./assets/css/main.css";
@import "./assets/css/color-dark.css"; /*深色主题*/
</style>复制代码

下面举例一下经常使用的装饰器使用web

<script lang="ts">
import Test from './test.vue';
import { Component, Prop, Provide, Vue, Watch  } from 'vue-property-decorator';
// 引入组件 即便没有使用组件也得书写 @Component,里面为空便可。
@Component({    
    components: {      
        Test    
    },  
})

 export default class Home extends Vue {
  // Prop 
    @Prop({}) private config: object = {};

  // data 
    private side: boolean = false;
    private list: object = {};
  
 // Watch
    @Watch('config')  
    onConfigChanged(val: any, oldVal: any) {    
        this.init();  
    }}

  // 生命周期
    private created(){
        this.init();
    }

  // 方法
    private init(){
        console.log('halo');
    }
</script>复制代码

其余的文件也是参照方式去修改便可。vue-router

最后从新运行就好了。express