草庐IT

uniapp+vue3 接入typescript

东扯葫芦西扯瓜 2023-03-28 原文

以下演示的编辑器使用HbuildX

首先安装typescript编译插件。下面演示从HbuildX安装

在HbuildX里面,依次找到 工具 -> 插件安装 -> 安装新插件 -> 前往插件市场安装


image.png

然后输入typescript,搜索,选择 typescript编译

image.png

这是因为typescript编译插件不是HbuildX的核心插件,只能去插件市场。因此,其实也可以直接访问 https://ext.dcloud.net.cn/search?q=typescript&cat1=1&cat2=11
搜索插件然后安装即可。安装好后,在已安装插件处可以看到

image.png

uniapp 对vue3+ts已经做了兼容,安装好插件后,基本就可以用vue3写了。由于uniapp 项目,通常的应用场景里面vue3都可以兼容,因此这里就不讨论vue2的写法,以下就做下vue3的示例
yl-phone-msg-code 插件地址:https://ext.dcloud.net.cn/plugin?id=8544

vue3 setup 组合式api写法,应用生命周期函数onLoad,onShow等和setUp同级

<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:'发送验证码'}"
        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="请输入用户名" />
        <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="请输入密码" />
        <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">{{ ["账号密码登录","验证码登录"][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">注册账号</view>-->
    <view class="regesterText row-center" @tap="goRegister">xxx信息技术有限责任公司</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: '', //正式时清除
      password: '', //正式时清除
    })
    let isLogin= ref(false)
    let loginMethod=ref(0)//登录方式 0 验证码 1 账号
    let hasGetCode=ref(false)//是否获取验证码
    let fromRouteInfo=ref({})//来源路由信息
    let customStyle=ref({
      color:"#ffffff"
    })// 自定义样式
    /**
     * 获取验证码
     * @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('请输入正确的用户名')
          return
        }
        if (!password) {
          showAlert('请输入正确的密码')
          return
        }
      }else if(loginMethod===0){
        if (!mobile) {
          showAlert('请输入手机号')
          return
        }
        if (!code) {
          showAlert('请输入短信验证码')
          return
        }
      }

      if(isLogin.value){
        uni.showToast({
          title:'正在登录,请稍后操作',
          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 || '网络错误!请稍后重试')
        },
        complete:()=> {
          // uni.hideLoading()
          isLogin.value=false
        }
      })

    }
    /**
     * 设置登录信息
     */
    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
      }
      //设置登录信息
      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){
        //没有手机号时去绑定
        uni.redirectTo({
          url:`/pages/bindPhone/bindPhone?${queryString}`
        })
      }else{
        backToFrom(fromRouteInfo.value)
      }
    }
    /**
     * 自动获取密码登陆
     * @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
      }
    }
    /**
     * 跳转注册
     */
    const goRegister = ():void => {
      uni.redirectTo({
        url:'../register/register'
      })
    }
    /**
     * 使用微信登录
     */
    const wxLogin = ():void => {
      uni.showLoading({title:'加载中'})
      // 获取用户信息
      uni.getUserProfile({
        desc:'用于完善会员资料,提升用户体验',
        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('调用微信登录成功')
                  console.log(res)
                  uni.hideLoading()
                  this.setLoginInfo(res,true)
                },
                fail:(err:any):void=>{
                  uni.hideLoading()
                  uni.showToast({
                    title:err.errMsg || '网络错误',
                    icon:'error'
                  })
                },
              })
            },
            fail:function (err:any):void{
              uni.showToast({
                title:'微信登录出错',
                icon:'error'
              })
            }
          })
        },
        fail():void{
          uni.hideLoading()
        }
      })
    }
    /**
     * 登录切换
     */
    const loginSwitch = ():void => {
      loginMethod.value = 1 - loginMethod.value
    }
    return {
      loginform,
      isLogin,
      loginMethod,//登录方式 0 验证码 1 账号
      hasGetCode,//是否获取验证码
      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>

有关uniapp+vue3 接入typescript的更多相关文章

  1. unity---接入Admob - 2

    目录1.AdmobSDK下载地址2.将下载好的unityPackagesdk导入到unity里​编辑 3.解析依赖到项目中

  2. 计算机毕业设计ssm+vue基本微信小程序的小学生兴趣延时班预约小程序 - 2

    项目介绍随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱小学生兴趣延时班预约小程序的设计与开发被用户普遍使用,为方便用户能够可以随时进行小学生兴趣延时班预约小程序的设计与开发的数据信息管理,特开发了小程序的设计与开发的管理系统。小学生兴趣延时班预约小程序的设计与开发的开发利用现有的成熟技术参考,以源代码为模板,分析功能调整与小学生兴趣延时班预约小程序的设计与开发的实际需求相结合,讨论了小学生兴趣延时班预约小程序的设计与开发的使用。开发环境开发说明:前端使用微信微信小程序开发工具:后端使用ssm:VU

  3. (附源码)vue3.0+.NET6实现聊天室(实时聊天SignalR) - 2

    参考文章搭建文章gitte源码在线体验可以注册两个号来测试演示图:一.整体介绍  介绍SignalR一种通讯模型Hub(中心模型,或者叫集线器模型),调用这个模型写好的方法,去发送消息。  内容有:    ①:Hub模型的方法介绍    ②:服务器端代码介绍    ③:前端vue3安装并调用后端方法    ④:聊天室样例整体流程:1、进入网站->调用连接SignalR的方法2、与好友发送消息->调用SignalR的自定义方法 前端通过,signalR内置方法.invoke()  去请求接口3、监听接受方法(渲染消息)通过new signalR.HubConnectionBuilder().on

  4. vue 实现内容超出两行显示展开更多功能,可依据需求自定义任意行数! - 2

    平时开发中我们经常会遇到这样的需求,在一个不限高度的盒子中会有很多内容,如果全部显示用户体验会非常不好,所以可以先折叠起来,当内容达到一定高度时,显示展开更多按钮,点击即可显示全部内容,先来看看效果图: 这样做用户体验瞬间得到提升,接下来看看具体细节。0">主要操作在内容这里{{item.username}},……展开更多样式大家可依据自己项目需求进行设计,这里就不贴了,主要说几个关键的。1、在data中定义三个属性isShowMore:false, //控制展开更多的显示与隐藏textHeight:null, //框中内容的高度status:false, //内容状态是否打开2.计算内容是否

  5. vue3.0 + vite2.0+如何兼容低版本浏览器 - 2

    这里写自定义目录标题一、问题二、解决三、解决方案四、打包预览一、问题在使用vue3.2和vite2开发一个移动端或者钉钉端H5微服务iosapp内置浏览器打开没问题安卓app内置浏览器打开空白页面vconsole打印出现报错globalthisundefind二、解决内置浏览器版本比较低打印出来是63vue3代码不兼容低版本浏览器三、解决方案步骤一:vite.config.ts里build.target配置项指定构建目标为es2015或者步骤二:安装@vitejs/plugin-legacy安装完报错也还在指定版本可以解决“@vitejs/plugin-legacy”:“1.8.0”,步骤三:

  6. 停车系统源码-基于springboot+uniapp开源项目 - 2

    Iparking停车收费管理系统-可商用介绍Iparking是一款基于springBoot的停车收费管理系统,支持封闭车场和路边车场,支持微信支付宝多种支付渠道,支持多种硬件,涵盖了停车场管理系统的所有基础功能。技术栈Springboot,MybatisPlus,Beetl,Mysql,Redis,RabbitMQ,UniApp功能云端功能序号模块功能描述1系统管理菜单管理配置系统菜单2系统管理组织管理管理组织机构3系统管理角色管理配置系统角色,包含数据权限和功能权限配置4系统管理用户管理管理后台用户5系统管理租户管理多租户管理6系统管理公众号配置租户公众号配置7系统管理操作日志审计日志8系统

  7. STM32+ESP8266接入云(3) - 2

    解析数据     进入阿里云的IOTStdio,点击新建项目。         新建项目后点击新建Web应用。名称     应用名称随便填写              创建完成后我们进入应用。    在左侧组件处拖入一个指示灯和一个开关。     点击指示灯组件,点击配置数据源     选择我们的产品、数据、和属性。     我们还可以配置开和关的显示颜色。    点击按钮,配置交互动作。     选择设备和属性,设置值位置点击数据来源,选择组件值     配置完成后进入预览,点击按钮,在esp8266就会收到来自平台的json格式的数据,MCU端需要做的就是解析来自平台的数据,进而达到控制下

  8. Vue3的新特性 - 2

    Vue3的新特性包括:CompositionAPI:一种新的API风格,可将有关组件功能的代码逻辑封装在单独的函数中,从而更好地管理和重用代码。Teleport:可以让组件在DOM层次结构中的任何位置渲染。Suspense:一种新的异步渲染模式,可以优化应用程序的性能。更快的渲染速度:Vue3使用了新的虚拟DOM算法,并且对渲染过程进行了优化,因此在渲染大型应用时性能更高。更小的包大小:Vue3的打包大小比Vue2更小,因为它不再需要依赖像vue-template-compiler这样的工具。其他改进:Vue3还具有其他一些改进,例如更好的TypeScript支持、更好的错误提示和更好的调试工

  9. Docker+HomeAssistant+HACS+设备接入教程 - 2

    homeassistant久仰大名,据说可以一统各大物联网平台的设备,家里各平台的设备都有一点,控制起来很不方便,于是乎我也来尝尝~homeassistant官网https://www.home-assistant.io/HACShttps://github.com/hacs/integration准备1.Linux系统(Window)其实也类似2.安装好dockerdocker安装homeassistant官方有几个版本可供选择,安装方式可以:直接刷HA的系统,也可以用Docker安装,还可以直接安装在物理机上,具体区别如下:我采用的是Docker进行安装,也就是Container,从上图也

  10. 【uniapp】uni.request请求跨域问题解决方案 - 2

    例如,运行H5页面,请求一个地址资源,如果不是本站地址,浏览器就会报跨域错误,这样访问受限问题呈现例如,项目代码里是这样写的,运行H5测试uni.request({ url:'https://gitcode.net/zs1028/stat...ouces_2023/-/...', success(res){ console.log(res) }, fail(err){ console.error(err) }})因为https://gitcode.net不是本站地址,根据浏览器同源策略,是会报跨域错误,解决步骤打开项目的manifest.json文件,以源码视图查看,添加以下代码{ //.

随机推荐