uni-app:利用Vue的原型对象Vue.prototype设置全局方法及其引用

一、在main.js中设置方法checkPermission绑定到Vue.prototype

核心代码

Vue.prototype.$checkPermission = function(username) {
  console.log('Checking permission for:', username);
};

完整代码

import App from './App'

// 添加 checkPermission 方法到 Vue.prototype 上,检查权限(这一段是方法的设置)
Vue.prototype.$checkPermission = function(username) {
  console.log('Checking permission for:', username);
};

// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App
})

app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

二、在页面引用全局方法

核心代码

this.$checkPermission(this.username);

完整代码

export default {
    data() {
        return {
            username: 'testuser'
        };
    },
    methods: {
        onLoad() {
            this.$checkPermission(this.username);//调用方法,传递参数username
        }
    }
};

补充:涉及到异步问题

一、main.js(全局方法有请求服务器的操作)

import App from './App'
// 添加 checkPermission 方法到 Vue.prototype 上,检查权限
Vue.prototype.$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);
      }
    });
  });
};




// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App
})

app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

二、userlogin.vue(调用方法)

methods: {
	//权限检查
	async checkUserPermission(username) {
		  try {
			const response = await this.$checkPermission(username);
			console.log('Server Response:', response);
			this.permissionResult = response.data; // 假设服务器返回的数据在response.data中
			this.permissionChecked = true;
		  } catch (error) {
			console.error('Error checking permission:', error);
		  }
	  },
    mounted() {
        // 页面加载时调用权限检查
        this.checkUserPermission('yourUsername');
    }

}

上一篇:ESP使用巴法云远程OTA(VScode + Platform io)


下一篇:Spring-DI入门案例