前言
氣勢洶涌,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';@Componentexport 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 /srcimport 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復制到工作區首位的項目的根目錄下,重啟編輯器,有比較大的概率可以解決警告提示。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答