說明:
vue3.0搭建的項目,不過沒有引入ts,后來需要用到一個插件是用ts寫的,所以vue要用到ts。。。
一、安裝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$/],
}
}
]
}
}
}
var path = require('path');
module.exports = {
outputDir:'vuecli3',
publicPath: './',
devServer: {
// 設置主機地址
host: 'localhost',
// 設置默認端口
// port: '8080',
// 打開瀏覽器
open: true,
port: 9000,
// 設置代理
// proxy: {
// '/api': {
// target: 'http://localhost:8081',
// pathRewrite: {
// '^/api': '/mock'
// }
// }
// }
},
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>