首页 资源列表 文章列表

uni.app:VUE3使用app.config.globalProperties,进行全局方法设置及其引用

在 Vue 3 中,Vue.prototype 已经被移除,取而代之的是通过 app.config.globalProperties 来添加全局方法

import { createSSRApp } from 'vue'
import App from './App'
 
export function createApp() {
  const app = createSSRApp(App)
 
  // 添加 checkPermission 方法到全局属性
  app.config.globalProperties.$checkPermission = function(username) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: getApp().globalData.position + 'Xcxuser/checkpermission',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: 'POST',
        dataType: 'json',
        data: {
          username: username,
        },
        success: res => {
          console.log('Server Response:', res);
          resolve(res);
        },
        fail: err => {
          console.log(err);
          reject(err);
        }
      });
    });
  };
 
  return {
    app
  }
}

页面进行引入

methods: {
	//权限检查
	async checkUserPermission(username) {
		try {
			const response = await this.$checkPermission(username);
			console.log('Server Response-页面:', response);
			getApp().globalData.permission = response.data;
			uni.setStorageSync('permission', response.data);
			uni.reLaunch({ //跳转到主页,并携带账号参数
				url: '/pages/index/index?username=' + username
				// url:'../../start_production/start_index/start_index?username=' + res.data[0].username
			})
		} catch (error) {
			console.error('Error checking permission:', error);
		}
	},
}

值得注意的是:在Vue3的 setup() 中,不可以直接访问 this ,需要通过访问 getCurrentInstance().proxy 全局方法。

0.123218s