章易 發表於 2020-11-11 13:42:00

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

<h3 id="一、安装typescript及loader">一、安装typescript及loader</h3>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">npm install typescript ts-loader --save-dev</pre>
</div>
<h3 id="二、安装vue-property-decorator">二、安装vue-property-decorator</h3>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">npm install vue-property-decorator --save-dev
</pre>
</div>
<h3 id="三、配置vueconfigjs">三、配置vue.config.js</h3>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">module.exports = {
configureWebpack: {   
    resolve: { extensions: [".ts", ".tsx", ".js", ".json"] },   
    module: {      
      rules: [   
      {   
          test: /\.tsx?$/,   
          loader: 'ts-loader',   
          exclude: /node_modules/,   
          options: {
            appendTsSuffixTo: [/\.vue$/],   
          }   
      }      
      ]   
    }   
}
}</pre>
</div>
<h3 id="四、新建tsconfigjson放在项目根目录">四、新建tsconfig.json放在项目根目录</h3>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">{
"compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "strictNullChecks": true,
    "esModuleInterop": true,
    "experimentalDecorators": true
}
}</pre>
</div>
<h3 id="五、在src目录下新建vue-shimdts文件">五、在src目录下新建vue-shim.d.ts文件</h3>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
</pre>
</div>
<h3 id="六、运行测试">六、运行测试</h3>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">&lt;template&gt;
        &lt;div&gt;
    &lt;el-button type="primary" @click="msgBtn"&gt;{{msg}}&lt;/el-button&gt;
    &lt;el-card shadow="always"&gt;
      {{test}}
    &lt;/el-card&gt;
        &lt;/div&gt;
&lt;/template&gt;
&lt;script lang='ts'&gt;
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)
    }
}
})

&lt;/script&gt;
</pre>
</div>
<p>  </p><br><br>
来源:https://www.cnblogs.com/yn-cn/p/13958261.html
頁: [1]
查看完整版本: vue-cli3 js项目中引入ts混用(typeScript)