用 Vue3 開發(fā)小程序,這里有一份實(shí)際的代碼案例!
前言
尋尋覓覓冷冷清清,凄凄慘慘戚戚。
Vue 3 發(fā)布以后,最近也在學(xué)習(xí)和寫一些 Vue3 的 demo 和項(xiàng)目,我也一直想著什么時(shí)候能在小程序里使用新特性?

于是我翻遍了市面上的小程序框架,如 uni-app、wepy、mpvue,目前(截止至2020年11月5日)還都沒能做到兼容 Vue 3 的寫法,直到我發(fā)現(xiàn)了一個(gè)很騷的東西, Taro 居然支持 Vue 3。

很驚喜!
開整
廢話少說,放碼過來,我們直接開整!
首先需要全局安裝 @tarojs/cli :
- # 使用 npm 安裝 CLI
 - $ npm install -g @tarojs/cli
 - # OR 使用 yarn 安裝 CLI
 - $ yarn global add @tarojs/cli
 - # OR 安裝了 cnpm,使用 cnpm 安裝 CLI
 - $ cnpm install -g @tarojs/cli
 
如果你的本地已經(jīng)安裝了 @tarojs/cli ,并且版本是 3.x,那么可以忽略上述操作。但是如過你的版本是 2.x,你需要先將它卸載了,再進(jìn)行上述安裝,卸載如下:
- $ npm uninstall -g @tarojs/cli
 - # 或者
 - $ yarn global remove @tarojs/cli
 
必要的話,兩個(gè)都執(zhí)行一遍。
這是我的版本號(hào):

初始化項(xiàng)目
通過如下命令行初始化項(xiàng)目:
- taro init taro-vue3
 
選項(xiàng)如下,這里要注意 CSS 預(yù)處理去選擇 Sass,后面 UI 框架會(huì)用到:

稍等一會(huì)兒,項(xiàng)目便可初始化完畢。
結(jié)束之后進(jìn)入項(xiàng)目,運(yùn)行指令:
- npm run dev:weapp
 
編譯成功之后,通過微信開發(fā)者工具打開 dist 目錄,瀏覽項(xiàng)目,如下所示:


UI 庫(kù)添加
要開發(fā)一個(gè)項(xiàng)目,雖然說不一定非要上 UI 庫(kù),但是有總比沒有好。純手寫樣式當(dāng)然也是考驗(yàn)一個(gè)前端工程師的技術(shù)功底,但是項(xiàng)目工期不等人,提高開發(fā)效率才是第一位。
在我查找 Taro 是否有 Vue 相關(guān)的 UI 庫(kù)時(shí),我找到了 taro-ui-vue ,感覺很舒服,應(yīng)該很快就可以寫出一個(gè) demo 來。
后來安裝好組件包,引入組件使用的時(shí)候,編譯出錯(cuò)了,大概看了一下,是沒有兼容 Vue 3 的寫法。
于是我打算暫時(shí)放棄了,然后到 taro-ui-vue 的倉(cāng)庫(kù)里提了一個(gè) Issue,如下所示:

我再一次沸騰了,居然還有這玩意兒 taro-ui-vue3 ,此時(shí)此刻我突然就很想和東哥做兄弟,哈哈哈哈。
繼續(xù)整!我們可以在項(xiàng)目里通過 npm install taro-ui-vue3 添加組件包,根據(jù)官網(wǎng)的提示,我這里采用了樣式全局引入的方式:
- // app.js
 - import { createApp } from 'vue'
 - import store from './store'
 - import 'taro-ui-vue3/dist/style/index.scss'
 - const App = createApp({
 - onShow (options) {},
 - // 入口組件不需要實(shí)現(xiàn) render 方法,即使實(shí)現(xiàn)了也會(huì)被 taro 所覆蓋
 - })
 - App.use(store)
 - export default App
 
頁(yè)面中直接通過引入組件使用:
- <template>
 - <view class="index">
 - <NumberDisplay/>
 - <NumberSubmit/>
 - <AtButton class="add-btn" type='primary'>測(cè)試</AtButton>
 - </view>
 - </template>
 - <script>
 - import NumberDisplay from '../../components/NumberDisplay.vue'
 - import NumberSubmit from '../../components/NumberSubmit.vue'
 - import { AtButton } from 'taro-ui-vue3'
 - export default {
 - name: 'Index',
 - components: {
 - NumberDisplay,
 - NumberSubmit,
 - AtButton
 - }
 - }
 - </script>
 - <style>
 - .index {
 - font-family: "Avenir", Helvetica, Arial, sans-serif;
 - -webkit-font-smoothing: antialiased;
 - -moz-osx-font-smoothing: grayscale;
 - text-align: center;
 - color: #2c3e50;
 - margin-top: 60px;
 - }
 - </style>
 
如下圖所示:

更多組件使用,請(qǐng)自行查閱 taro-ui-vue3 官方文檔 。
最后
本文主要就是為了安利大家一個(gè)能用 Vue 3 語(yǔ)法寫小程序的框架,在此我也基于上述代碼實(shí)踐了一下,制作了一個(gè) TodoList 小案例:

源代碼已經(jīng)開源到 GitHub vue3-examples 倉(cāng)庫(kù)中,倉(cāng)庫(kù)地址: vue3-examples ,此倉(cāng)庫(kù)將不定期更新各種 Vue3.0 相關(guān)的知識(shí)及各種整合 Demo 及 Vue3 使用小技巧,大家可以關(guān)注一下,有什么建議也歡迎大家給我留言。
除注明轉(zhuǎn)載/出處外,皆為作者原創(chuàng),歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁(yè)面明顯位置給出原文鏈接,否則保留追究法律責(zé)任的權(quán)利。















 
 
 










 
 
 
 