vue-cli3+typescript初體驗
前言
氣勢洶湧,ts似乎已經在來的路上,隨時可能敲門。
2015年,三大前端框架開始火爆的時候,我還在抱著Backbone不放,一直覺得可以輕易轉到其他框架去。後來換工作,現實把臉都打腫了,沒做過vue、react、angular?不要!
今天,不能犯這個錯了,畢竟時不我與,都快奔三了。
vue-cli3
vue-cli3 的詳細功能推薦官方文件,不在本文介紹範圍內。
安裝:
npm install -g @vue/cli
檢查安裝成功與否:
vue --version
建立專案:
vue create myapp
可以選擇Manually select feature
來自由選擇功能,常用的有vuex、vue-router、CSS Pre-processors等,我們再把typescript勾上,就可以回車進入下一步了。PS:勾選的操作是按空格鍵。
建立成功之後,執行啟動命令:
npm run serve
就可以通過http://localhost:8080/
訪問本地專案啦。
typescript
如果沒有typescript基礎,可以先補補課,大概花三十分鐘就可以瞭解typescript的一些特性,比如:TypeScript 入門教程 。
ts最主要的一點就是型別定義,有個概念才好看得懂demo。
vue-property-decorator
這是一個涵蓋了vue的一些物件的集合,我們可以從這裡取一些東西出來:
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
取出來的這幾個屬性,分別是 元件定義Component
,父元件傳遞過來的引數Prop
,原始vue物件Vue
,資料監聽物件Watch
。還包括這裡沒有列舉出來的Model
,Emit
,Inject
,Provide
,可以自己嘗試下。
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沒有引入元件,如果需要引入元件,應該這樣書寫:
<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複製到工作區首位的專案的根目錄下,重啟編輯器,有比較大的概率可以解決警告提示。