vue-cli3+typescript初体验

前言

气势汹涌,ts彷佛已经在来的路上,随时可能敲门。
2015年,三大前端框架开始火爆的时候,我还在抱着Backbone不放,一直以为能够轻易转到其余框架去。后来换工做,现实把脸都打肿了,没作过vue、react、angular?不要!
今天,不能犯这个错了,毕竟时不我与,都快奔三了。
以前写的一个demo,这一个多月太忙,没有继续下去,能够参看一下 vue-cli3-typescripthtml

vue-cli3

vue-cli3的详细功能推荐官方文档,不在本文介绍范围内。
安装:前端

npm install -g @vue/cli

检查安装成功与否:vue

vue --version

建立项目:react

vue create myapp

能够选择Manually select feature来自由选择功能,经常使用的有vuex、vue-router、CSS Pre-processors等,咱们再把typescript勾上,就能够回车进入下一步了。PS:勾选的操做是按空格键。
建立成功以后,执行启动命令:git

npm run serve

就能够经过http://localhost:8080/访问本地项目啦。github

typescript

若是没有typescript基础,能够先补补课,大概花三十分钟就能够了解typescript的一些特性,好比:TypeScript 入门教程
ts最主要的一点就是类型定义,有个概念才好看得懂demo。vue-router

vue-property-decorator

这是一个涵盖了vue的一些对象的集合,咱们能够从这里取一些东西出来:vuex

import { Component, Prop, Vue, Watch } from 'vue-property-decorator';

取出来的这几个属性,分别是 组件定义Component,父组件传递过来的参数Prop,原始vue对象Vue,数据监听对象Watch。还包括这里没有列举出来的ModelEmitInjectProvide,能够本身尝试下。vue-cli

demo

<template>
  <div class="hello">
    <h1>{{ msg }}--{{ names }}</h1>
    <input type="text" v-model="txt">
    <p>{{ getTxt }}</p>
    <button @click="add">add</button>
    <p>{{ sum }}</p>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';

@Component
export default class HelloWorld extends Vue {
  //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没有引入组件,若是须要引入组件,应该这样书写:typescript

<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复制到工做区首位的项目的根目录下,重启编辑器,有比较大的几率能够解决警告提示。
推荐阅读官方的vue+typescript文档

相关文章
相关标签/搜索