uniapp+vue3 接入typescript

以下演示的編輯器使用HbuildX

首先安裝typescript編譯插件改基。下面演示從HbuildX安裝

在HbuildX里面盼砍,依次找到 工具 -> 插件安裝 -> 安裝新插件 -> 前往插件市場(chǎng)安裝


image.png

然后輸入typescript,搜索,選擇 typescript編譯

image.png

這是因?yàn)閠ypescript編譯插件不是HbuildX的核心插件瓦糕,只能去插件市場(chǎng)空另。因此狸臣,其實(shí)也可以直接訪問 https://ext.dcloud.net.cn/search?q=typescript&cat1=1&cat2=11
搜索插件然后安裝即可粉寞。安裝好后尼荆,在已安裝插件處可以看到

image.png

uniapp 對(duì)vue3+ts已經(jīng)做了兼容,安裝好插件后唧垦,基本就可以用vue3寫了捅儒。由于uniapp 項(xiàng)目,通常的應(yīng)用場(chǎng)景里面vue3都可以兼容振亮,因此這里就不討論vue2的寫法巧还,以下就做下vue3的示例
yl-phone-msg-code 插件地址:https://ext.dcloud.net.cn/plugin?id=8544

vue3 setup 組合式api寫法,應(yīng)用生命周期函數(shù)onLoad,onShow等和setUp同級(jí)

<template>
  <view class="container">
    <view class="app-top-box column-center">
      <view class="kedang-app-img"></view>
      <view class="row-center kedang-text">
        歡迎光臨
      </view>
    </view>
    <yl-phone-msg-code
        v-if="loginMethod===0"
        mobile-prepend="+86"
        :req-mobile-code="getCode"
        :mobile-style="customStyle"
        :mobile-prepend-style="customStyle"
        :code-style="customStyle"
        :msg-code-text-config="{getCodeText:'發(fā)送驗(yàn)證碼'}"
        class="userLogin"
    >
      <template #getCode="{msgCodeText}">
        <view class="getCode">
          <view class="getCodeInner">{{ msgCodeText }}</view>
        </view>
      </template>
    </yl-phone-msg-code>
    <view class="userLogin" v-if="loginMethod===1">
      <view class="inputbox">
        <input type="text" v-model.trim="loginform.username" placeholder-class="input-placeholder" placeholder="請(qǐng)輸入用戶名" />
        <view class="row-center clearBox">
          <image v-if="loginform.username" src="../../static/login/close.png" class="clear" @tap="loginform.username=''"></image>
        </view>
      </view>
      <view class="inputbox">
        <input type="password" v-model.trim="loginform.password" placeholder-class="input-placeholder" placeholder="請(qǐng)輸入密碼" />
        <view class="row-center clearBox">
          <image v-if="loginform.password" src="../../static/login/close.png" class="clear" @tap="loginform.password=''"></image>
        </view>
      </view>
    </view>
    <view class="read-"></view>
    <view class="row-center b-btn-box" style="margin-top:40rpx;">
      <button class="u-btn" hover-class="u-hover-btn" @tap="onLogin">登錄</button>
    </view>
    <view class="row-center login-switch" @click="loginSwitch">{{ ["賬號(hào)密碼登錄","驗(yàn)證碼登錄"][loginMethod] }}</view>
<!--    <view class="row-end findPassBox">-->
<!--      <navigator class="navigator" url="/pages/findPassword/findPassword" hover-class="navigator-hover">-->
<!--        <text class="findPassText">找回密碼</text>-->
<!--      </navigator>-->
<!--    </view>-->

    <view class="wxLoginBox">
      <view class="otherLoginBox row-center">
        <view class="line"></view>
        <view class="text">其他登陸方式</view>
        <view class="line"></view>
      </view>
      <view class="row-center">
        <image class="wxImg" src="../../static/login/wx.png" @tap="wxLogin"></image>
      </view>
    </view>
<!--    <view class="regesterText row-center" @tap="goRegister">注冊(cè)賬號(hào)</view>-->
    <view class="regesterText row-center" @tap="goRegister">xxx信息技術(shù)有限責(zé)任公司</view>
  </view>
</template>

<script lang="ts">
import { defineComponent,ref } from 'vue'
import {useStore} from "vuex";
import {reqMobileCode} from "../../api/common"
import {preventContinuePoint,showAlert,backToFrom,jsonToqs} from "../../utils/util"
import { apiBaseUrl } from '../../utils/config.js'

export default defineComponent({
  onLoad({fromPath,isTab,options}):void{
    this.autocommplete()
    this.fromRouteInfo={fromPath,isTab,options}
  },
  onShow():void{
    this.autocommplete()
  },
  setup(props,context) {
    let store=useStore();
    let loginform= ref({
      username: '', //正式時(shí)清除
      password: '', //正式時(shí)清除
    })
    let isLogin= ref(false)
    let loginMethod=ref(0)//登錄方式 0 驗(yàn)證碼 1 賬號(hào)
    let hasGetCode=ref(false)//是否獲取驗(yàn)證碼
    let fromRouteInfo=ref({})//來源路由信息
    let customStyle=ref({
      color:"#ffffff"
    })// 自定義樣式
    /**
     * 獲取驗(yàn)證碼
     * @param mobile
     * @param code
     * @returns {Promise<void>}
     */
    const getCode = async (mobile:string,code:string):Promise<any> => {
      let result = await reqMobileCode(mobile)
      console.log(result)
      loginform.value= {mobile,code}
      hasGetCode.value=true
    }
    /**
     * 登錄
     * @returns {Promise<void>}
     */
    const onLogin = async ():Promise<any>  => { //status == 426 用戶不存在
      await preventContinuePoint(this)
      let {username,password,code,mobile} = loginform.value
      if(loginMethod.value===1){
        if (!username) {
          showAlert('請(qǐng)輸入正確的用戶名')
          return
        }
        if (!password) {
          showAlert('請(qǐng)輸入正確的密碼')
          return
        }
      }else if(loginMethod===0){
        if (!mobile) {
          showAlert('請(qǐng)輸入手機(jī)號(hào)')
          return
        }
        if (!code) {
          showAlert('請(qǐng)輸入短信驗(yàn)證碼')
          return
        }
      }

      if(isLogin.value){
        uni.showToast({
          title:'正在登錄坊秸,請(qǐng)稍后操作',
          icon:'none'
        })
        return
      }
      isLogin.value = true
      uni.showLoading({
        title: '登錄中...'
      })
      console.log(apiBaseUrl)
      uni.request({
        url: apiBaseUrl + ['auth/login_by_code','auth/login',][loginMethod],
        method:'POST',
        data:loginform.value,
        timeout: 1000 * 5,
        success:res=> {
          uni.hideLoading()
          console.log(res);
          //登錄成功
          uni.setStorageSync('loginUser', {
            username,
            password,
            checked: true
          })
          setLoginInfo(res)
        },
        fail:err=> {
          uni.hideLoading()
          console.log(err);
          let msg=err.msg
          isLogin.value = false
          showAlert(msg || '網(wǎng)絡(luò)錯(cuò)誤麸祷!請(qǐng)稍后重試')
        },
        complete:()=> {
          // uni.hideLoading()
          isLogin.value=false
        }
      })

    }
    /**
     * 設(shè)置登錄信息
     */
    const setLoginInfo = (res:any,isWx?:boolean):any => {
      let {errmsg,errno,data}=res.data
      console.log(errno)
      if(errno!==0){
        uni.showToast({
          title:errmsg,
          icon:'error'
        })
        return
      }
      //設(shè)置登錄信息
      uni.setStorage({
        key: 'hasLogin',
        data: 1,
      })
      let {token,userInfo}=res.data.data
      uni.setStorage({
        key: 'token',
        data: token,
      })
      userInfo.originUserType=userInfo.userType
      store.dispatch('setLoginInfo', userInfo)
      uni.setStorage({
        key:'userInfo',
        data:userInfo
      })
      let queryString=jsonToqs(fromRouteInfo.value)
      queryString=decodeURIComponent(queryString)
      if(isWx && !userInfo.mobile){
        //沒有手機(jī)號(hào)時(shí)去綁定
        uni.redirectTo({
          url:`/pages/bindPhone/bindPhone?${queryString}`
        })
      }else{
        backToFrom(fromRouteInfo.value)
      }
    }
    /**
     * 自動(dòng)獲取密碼登陸
     * @returns {Promise<void>}
     */
    const autocommplete = async ():Promise<any> => {
      let loginUser = await uni.getStorageSync('loginUser')
      if (loginUser.username) {
        loginform.value.username = loginUser.username
        loginform.value.password = loginUser.password
      }
    }
    /**
     * 跳轉(zhuǎn)注冊(cè)
     */
    const goRegister = ():void => {
      uni.redirectTo({
        url:'../register/register'
      })
    }
    /**
     * 使用微信登錄
     */
    const wxLogin = ():void => {
      uni.showLoading({title:'加載中'})
      // 獲取用戶信息
      uni.getUserProfile({
        desc:'用于完善會(huì)員資料,提升用戶體驗(yàn)',
        success: infoRes=> {
          console.log(infoRes)
          uni.login({
            provider: 'weixin',
            onlyAuthorize:true,
            success: async (loginRes:any):Promise<any> => {
              console.log(loginRes.code)
              console.log(loginRes)
              uni.request({
                url:apiBaseUrl +'auth/login_by_weixin',
                data:{
                  code: loginRes.code,
                  userInfo: infoRes.userInfo
                },
                method:'POST',
                success:(res:any)=>{
                  console.log('調(diào)用微信登錄成功')
                  console.log(res)
                  uni.hideLoading()
                  this.setLoginInfo(res,true)
                },
                fail:(err:any):void=>{
                  uni.hideLoading()
                  uni.showToast({
                    title:err.errMsg || '網(wǎng)絡(luò)錯(cuò)誤',
                    icon:'error'
                  })
                },
              })
            },
            fail:function (err:any):void{
              uni.showToast({
                title:'微信登錄出錯(cuò)',
                icon:'error'
              })
            }
          })
        },
        fail():void{
          uni.hideLoading()
        }
      })
    }
    /**
     * 登錄切換
     */
    const loginSwitch = ():void => {
      loginMethod.value = 1 - loginMethod.value
    }
    return {
      loginform,
      isLogin,
      loginMethod,//登錄方式 0 驗(yàn)證碼 1 賬號(hào)
      hasGetCode,//是否獲取驗(yàn)證碼
      fromRouteInfo,//來源路由信息
      customStyle,// 自定義樣式
      getCode,
      onLogin,
      setLoginInfo,
      autocommplete,
      goRegister,
      wxLogin,
      loginSwitch
    }
  },
})
</script>

<style lang="scss" scoped>
.container {
  background: #13141a;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
  padding-top:170rpx;
}
.app-top-box{
  margin-bottom: 100rpx;
  border:solid 1px blue;
  .kedang-app-img{
    width: 160rpx;
    height: 160rpx;
    border:solid 1px red;
    margin-bottom: 20rpx;
  }
  .kedang-text{
    color:#ffffff;
  }
}
.userLogin{
  height:200rpx;
}
.wxLoginBox{
  //margin-top:124rpx;
  //margin-bottom: 88rpx;
  .otherLoginBox{
    margin-bottom: 40rpx;
    .line{
      width: 144rpx;
      height: 1rpx;
      background: #EEEEEE;
    }
    .text{
      font-size: 24rpx;
      color:#aaaaaa;
      margin:0 10rpx;
    }
  }
  .wxImg{
    width:96rpx;
    height:96rpx;
  }
}
.login-switch{
  margin-top:40rpx;
  color:#999999;
  margin-bottom: 100rpx;
}
.regesterText{
  font-size: 24rpx;
  color:#666666;
}
.findPassBox{
  padding:20rpx 30rpx;
}
.findPassText{
  color:#3F99FF;
}
.getCode{
  background: linear-gradient(90deg,#f6b847, #f1950e);
  padding:2rpx;
  border-radius: 30rpx;
  overflow: hidden;
  .getCodeInner{
    width: 160rpx;
    font-size: 20rpx;
    text-align: center;
    color: #faad14;
    background: #13141a;
    padding:10rpx 20rpx;
    border-radius: 30rpx;
    overflow: hidden;
  }
}
</style>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末褒搔,一起剝皮案震驚了整個(gè)濱河市阶牍,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌星瘾,老刑警劉巖走孽,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異琳状,居然都是意外死亡磕瓷,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門算撮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來生宛,“玉大人县昂,你說我怎么就攤上這事∠菥耍” “怎么了倒彰?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)莱睁。 經(jīng)常有香客問我待讳,道長(zhǎng),這世上最難降的妖魔是什么仰剿? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任创淡,我火速辦了婚禮,結(jié)果婚禮上南吮,老公的妹妹穿的比我還像新娘琳彩。我一直安慰自己,他們只是感情好部凑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布露乏。 她就那樣靜靜地躺著,像睡著了一般涂邀。 火紅的嫁衣襯著肌膚如雪瘟仿。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天比勉,我揣著相機(jī)與錄音劳较,去河邊找鬼。 笑死浩聋,一個(gè)胖子當(dāng)著我的面吹牛观蜗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播赡勘,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼嫂便,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了闸与?” 一聲冷哼從身側(cè)響起毙替,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎践樱,沒想到半個(gè)月后厂画,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡拷邢,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年袱院,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡忽洛,死狀恐怖腻惠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情欲虚,我是刑警寧澤集灌,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站复哆,受9級(jí)特大地震影響欣喧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜梯找,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一唆阿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧锈锤,春花似錦驯鳖、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至妄壶,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間寄狼,已是汗流浹背丁寄。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留泊愧,地道東北人伊磺。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像删咱,于是被迫代替她去往敵國和親屑埋。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容