vue-cli3 js项目中引入ts混用(typeScript)

一、安装typescript及loader

npm install typescript ts-loader --save-dev

二、安装vue-property-decorator

npm install vue-property-decorator --save-dev

三、配置vue.config.js

module.exports = {
 configureWebpack: {    
    resolve: { extensions: [".ts", ".tsx", ".js", ".json"] },    
    module: {        
      rules: [    
        {    
          test: /.tsx?$/,    
          loader: 'ts-loader',    
          exclude: /node_modules/,    
          options: {
            appendTsSuffixTo: [/.vue$/],    
          }    
        }        
      ]    
    }    
  }  
}

四、新建tsconfig.json放在项目根目录

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "strictNullChecks": true,
    "esModuleInterop": true,
    "experimentalDecorators": true
  }
}

五、在src目录下新建vue-shim.d.ts文件

declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

六、运行测试

<template>
	<div>
    <el-button type="primary" @click="msgBtn">{{msg}}</el-button>
    <el-card shadow="always">
      {{test}}
    </el-card>
	</div>
</template>
<script lang='ts'>
import { Component, Vue } from "vue-property-decorator";

export default Vue.extend({
  components: {
    // TableCom
  },
  data() {
    return {
      msg:'typescript'
    };
  },
  created(){
    console.log('created',this.msg)
  },
  mounted() {
    console.log('mounted')
  },
  computed:{
    // test: {
    //   // 需要标注有 `this` 参与运算的返回值类型
    //   get(): string {
    //     return this.msg
    //   },
    //   set(val: string) {
    //     this.msg = val
    //   }
    // }
    test(): any {
      return this.msg
    }
  },
  watch:{
    msg(val:any){
      console.log('watch',val)
    }
  },
  methods:{
    msgBtn(ev:any){
      this.msg = "更改了typescript"
      console.log('点击事件',ev)
    }
  }
})

</script>

  

原文地址:https://www.cnblogs.com/yn-cn/p/13958261.html