vue3+ts+uniapp小程序封装获取授权hook函数

文章介绍了如何在Vue3和TypeScript的UniApp小程序中封装一个全局的授权提示函数,解决用户拒绝授权后不再弹出的问题,通过uni-appAPI实现授权请求和引导用户手动设置授权。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue3+ts+uniapp小程序封装获取授权hook函数

小程序授权的时候,如果点击拒绝授权,然后就再也不会出现授权了,除非用户手动去右上角…设置打开

通过uni官方api自己封装一个全局的提示:
uni.getSetting :http://uniapp.dcloud.io/api/other/setting?id=getsetting
uni.authorize:http://uniapp.dcloud.io/api/other/authorize?id=authorize
uni.openSetting:https://uniapp.dcloud.net.cn/api/other/setting.html#opensetting

具体代码
src\composable\index.ts

/**
 * 授权综合逻辑
 * @param {*} scope 权限代表
 */
export const useShowPullAuth = () => {
  const pullAuth = (scope: keyof UniApp.AuthSetting): void => {
    const map: Record<string, string> = {
      'scope.userInfo': '用户信息',
      'scope.userLocation': '地理位置',
      'scope.userLocationBackground': '后台定位',
      'scope.address': '通信地址',
      'scope.record': '录音功能',
      'scope.writePhotosAlbum': '保存到相册',
      'scope.camera': '摄像头',
      'scope.invoice': '获取发票',
      'scope.invoiceTitle': '发票抬头',
      'scope.werun': '微信运动步数',
    }

    uni.getSetting({
      success() {
        // scope 存在
        if (map[scope]) {
          // 提前向用户发起授权请求
          uni.authorize({
            scope,
            fail() {
              const word = map[scope]
              uni.showModal({
                content: `检测到您没打开${word}权限,是否去设置打开?`,
                confirmText: '确认',
                cancelText: '取消',
                success: (res) => {
                  if (res.confirm) {
                    // 打开授权页
                    uni.openSetting({
                      success: (res) => {
                        if (res.authSetting[scope]) {
                          uni.showToast({
                            title: '授权成功',
                            icon: 'none',
                          })
                        } else {
                          uni.showToast({
                            title:
                              '未授权,将会影响使用小程序部分功能,可自行去右上角(...)中-设置手动打开!',
                            icon: 'none',
                          })
                        }
                      },
                    })
                  } else {
                    uni.showToast({
                      title:
                        '未授权,将会影响使用小程序部分功能,可自行去右上角(...)中-设置手动打开!',
                      icon: 'none',
                      duration: 2500,
                    })
                  }
                },
              })
            },
          })
        } else {
          // 不存在授权 scope
          uni.showToast({
            title: '无此授权功能',
            icon: 'none',
          })
        }
      },
    })
  }
  return { pullAuth }
}

在需要用的页面使用 onLoad

放在onLoad是为了一进来就进行调用,当scope是对的就会进行发起授权,当你之前已经授权过了,就会什么也不做,若是发现未授权,就会弹窗手动引导你去系统授权设置里!

<script setup lang="ts">
import { useShowPullAuth } from '@/composable'
import { onLoad } from '@dcloudio/uni-app'
onLoad(() => {
  console.log('onLoad')
  pullAuth('scope.camera')
})
</script>

在这里插入图片描述

### ### Vue 3TypeScript 的结合实现方式 Vue 3TypeScript 提供了原生支持,开发者可以通过使用 `script setup` 语法或传统的选项式 API 来实现类型安全和更好的开发体验。在 Vue 3 中结合 TypeScript,不仅可以提升代码的可维护性,还能增强组件之间的类型检查能力[^1]。 #### 使用 `script setup` 与 TypeScript Vue 3 的 `script setup` 语法为 TypeScript 提供了良好的集成体验,开发者可以在 `<script setup>` 中直接使用类型注解和泛型。例如,定义一个带有类型注解的响应式变量: ```vue <script setup lang="ts"> import { ref } from &#39;vue&#39; const count = ref<number>(0) const increment = () => { count.value++ } </script> <template> <button @click="increment">Count: {{ count }}</button> </template> ``` 在该示例中,`count` 被明确指定为 `number` 类型,任何尝试赋值非数字类型的操作都会被 TypeScript 捕获。 #### 使用组合式 API 与自定义 Hook Vue 3 支持通过组合式 API 将逻辑复用逻辑封装为可重用的函数。例如,定义一个 `useSum` 函数来管理数值状态: ```ts // useSum.ts import { ref, onMounted } from &#39;vue&#39; export default function useSum() { const sum = ref<number>(0) const increment = () => { sum.value += 1 } const decrement = () => { sum.value -= 1 } onMounted(() => { increment() }) return { sum, increment, decrement } } ``` 在组件中使用该 Hook: ```vue <script setup lang="ts"> import useSum from &#39;./useSum&#39; const { sum, increment } = useSum() </script> <template> <div>当前总和:{{ sum }}</div> <button @click="increment">增加</button> </template> ``` 通过这种方式,可以将业务逻辑从组件中解耦,提高代码的复用性和可测试性[^2]。 #### 使用 Pinia 进行状态管理 在 Vue 3 + TypeScript 项目中,推荐使用 [Pinia](https://pinia.vuejs.org/) 替代 Vuex 作为状态管理方案,因为它对 TypeScript 的支持更加友好。定义一个 Pinia Store 并使用 TypeScript 注解类型: ```ts // stores/counterStore.ts import { defineStore } from &#39;pinia&#39; export const useCounterStore = defineStore(&#39;counter&#39;, { state: () => ({ count: 0, }), actions: { increment() { this.count++ }, decrement() { this.count-- }, }, }) ``` 在组件中使用该 Store: ```vue <script setup lang="ts"> import { useCounterStore } from &#39;@/stores/counterStore&#39; const counter = useCounterStore() </script> <template> <div>当前计数:{{ counter.count }}</div> <button @click="counter.increment()">增加</button> </template> ``` Pinia 的类型推导能力可以确保状态和操作的类型安全,同时提供良好的开发体验[^3]。 #### 路由管理与 TypeScript Vue 3 推荐使用 Vue Router 4,它也提供了对 TypeScript 的良好支持。定义带有类型注解的路由配置: ```ts // router/index.ts import { createRouter, createWebHistory } from &#39;vue-router&#39; import HomeView from &#39;../views/HomeView.vue&#39; const router = createRouter({ history: createWebHistory(), routes: [ { path: &#39;/&#39;, name: &#39;home&#39;, component: HomeView, }, { path: &#39;/about&#39;, name: &#39;about&#39;, component: () => import(&#39;../views/AboutView.vue&#39;), }, ], }) export default router ``` 在组件中使用路由: ```vue <template> <nav> <router-link to="/">首页</router-link> <router-link to="/about">关于</router-link> </nav> <router-view /> </template> ``` 通过上述方式,可以在 Vue 3 项目中充分结合 TypeScript,提升代码的可读性、可维护性和类型安全性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值