vue3注冊(cè)全局方法代替vue2的Vue.prototype.xxx

vue3.0

最近要用uniapp新整個(gè)兼容支付寶和微信的小程序,尋思了一下,搞搞vue3的吧,又一尋思別老用try,catch了吧,試試await-to-js唄
說(shuō)整就整,npm i await-to-js,來(lái)到main.ts文件,自信一手來(lái)了波操作

import Vue from 'vue'
import to from 'await-to-js';
Vue.prototype.$to = to

緊接著就漏出了馬腳,prototype飄紅了:

 Property 'prototype' does not exist on type 'typeof import("/Users/jryg/www/uniapp-v3-ts-pinia/node_modules/vue/dist/vue")'.ts(2339)

查了下,Vue3人家不這么用,看了看大概分兩種

1. 使用 config.globalProperties

// main.ts
import { createSSRApp } from "vue"
const app = createSSRApp(App)
app.config.globalProperties.$to = to
// 使用文件 setup
import { getCurrentInstance } from 'vue'
const instance = getCurrentInstance()?.proxy
console.log(instance?.$to)

使用instance?.$to 發(fā)現(xiàn)飄紅,提示大概意思是intance上沒(méi)有$to,那咱就去加一個(gè)唄

// shime-uni.d.ts
import to from 'await-to-js'; 
declare module "vue" {
   interface ComponentCustomProperties{
     $to: typeof to;
  } 
}

至此看到控制臺(tái)已經(jīng)打印出來(lái),舒服搞定,接下來(lái)看第二種

2. 使用provide/inject

// main.ts
import { createSSRApp } from "vue"
const app = createSSRApp(App)
app.provide($to,  to)
// 使用文件 setup
import { inject } from 'vue'
const $to = inject('$to')
console.log($to)
//? to(promise, errorExt) {
//  return promise.then(function (data) {
//    return [null, data];
//  }).catch(function (err) {
//    if (errorExt) {
//      Object.assign(err, errorExt);
//   }
//    return [err, voi…
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容