vue-cli3+typescript初体验小结

2020-06-13 10:42:17易采站长站整理

//props
@Prop() private msg!: string
@Prop() private names!: string
//data
private txt: string = '1'
private sum: number = 0
//computed
get getTxt(){
return this.txt
}
//methods
private add(){
this.sum++
console.log(`sum : ${this.sum}`)
}
//生命周期
created(){
console.log('created')
}
//watch
@Watch('txt')
changeTxt(newTxt: string, oldTxt: string){
console.log(`change txt: ${oldTxt} to ${newTxt}`)
}

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h3 {
margin: 40px 0 0;
}
input {
width: 240px;
height: 32px;
line-height: 32px;
}
</style>

以上就是demo,代码组织有点散,没有原来js书写的整齐。

这个demo没有引入组件,如果需要引入组件,应该这样书写:


<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" names="aaa" />
<HelloWorld2 msg="Welcome to Your Vue.js + TypeScript App" names="bbb" />
</div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
import HelloWorld2 from '@/components/HelloWorld2.vue'; // @ is an alias to /src

@Component({
components: {
HelloWorld,
HelloWorld2,
},
})
export default class Home extends Vue {}
</script>

结语

如果VSCode编辑器有警告提示,比如:

Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.

可以把工作区其他的项目移除,或者把本项目拖动到工作区的首位,或者在把本项目的tsconfig.json复制到工作区首位的项目的根目录下,重启编辑器,有比较大的概率可以解决警告提示。