uni-app vue3公共方法定义,之前提到过一种,参见:uni-app vue3版store使用和在Vue3中使用Vue.prototype。但这种由于用到了this,在使用时,如果是composition api或setup语法糖,会更加麻烦,这里推荐一个方法,直接挂载到uni这个全局对象上。
以uni-app vue3版store使用为例,首先改造main.js,将:
app.config.globalProperties.$store = store
改成
uni.$store = store
使用时,原先要:
import {getCurrentInstance} from 'vue'
const { proxy } = getCurrentInstance();//获取公用方法proxy.$axios,或者use中方法
const {$store}=proxy
// 调用store里的方法
$store.commit('login', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9')
// 使用store里的值
console.log($store.state.token)现在只要:
// 调用store里的方法
uni.$store.commit('login', 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9')
// 使用store里的值
console.log(uni.$store.state.token)