欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3+ts+setup?getCurrentInstance使用時(shí)遇到的問(wèn)題以及解決辦法

 更新時(shí)間:2022年08月10日 10:20:54   作者:豌里個(gè)豆  
getCurrentInstance方法用于獲取當(dāng)前組件實(shí)例,僅在setup和生命周期中起作用,下面這篇文章主要給大家介紹了關(guān)于Vue3+ts+setup?getCurrentInstance使用時(shí)遇到的問(wèn)題以及解決辦法,需要的朋友可以參考下

環(huán)境

vscode
typescript4
vue3

問(wèn)題描述

首先,vue3中的全局變量及方法的配置較vue2中的變化大家應(yīng)該已經(jīng)知道了,不清楚的可以查看官方說(shuō)明,但是按照官方文檔結(jié)合typescript使用時(shí)遇到了問(wèn)題:

axios.ts

// axios.ts
import axios from 'axios'
const app = Vue.createApp({})

// 全局自定義屬性
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

app.config.globalProperties.$axios = axios

任意.vue文件

<script lang="ts" setup>
import { getCurrentInstance } from 'vue';

// 首先 此處 proxy ts會(huì)報(bào)
// 類型“ComponentInternalInstance | null”上不存在屬性“proxy”。ts(2339)
const { proxy } = getCurrentInstance()

// 然后下面會(huì)報(bào)這個(gè)錯(cuò)誤
// Unsafe member access .$axios on an `any` value.  eslint@typescript-eslint/no-unsafe-member-access
// Unsafe call of an `any` typed value.  eslint@typescript-eslint/no-unsafe-call
proxy.$axios('')

以上就是報(bào)錯(cuò)的全部?jī)?nèi)容,接下來(lái)我們解決這個(gè)問(wèn)題

問(wèn)題解決

  • 第一個(gè)報(bào)錯(cuò)很好理解 因?yàn)?nbsp;getCurrentInstance()的返回類型存在null所以在此處添加斷言即可
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加斷言
const { proxy } = getCurrentInstance() as ComponentInternalInstance

2.但是改完后我們發(fā)現(xiàn)下面依舊會(huì)有報(bào)錯(cuò)

// 對(duì)象可能為 "null"。ts(2531)
proxy.$axios('')

這個(gè)解決起來(lái)更簡(jiǎn)單了,在proxy后面添加?來(lái)過(guò)濾null的結(jié)果

proxy?.$axios('')

以上,問(wèn)題解決!

補(bǔ)充:Vue3 getCurrentInstance與ts結(jié)合使用的坑

一、關(guān)于在ts中使用到類型定義錯(cuò)誤問(wèn)題

報(bào)錯(cuò):...類型“ComponentInternalInstance | null”

就嗝屁了。。。

1. 可以添加ts忽略去解決

// @ts-ignoreconst { proxy } = getCurrentInstance();

但是這個(gè)方法很無(wú)腦,也麻煩。。。

2. 考慮到在獲取上下文和全局掛載實(shí)例的時(shí)候會(huì)用到這個(gè)getCurrentInstance,那我們來(lái)新建 hooks\useCurrentInstance.ts

import { ComponentInternalInstance, getCurrentInstance } from 'vue'export defaultfunction useCurrentInstance() {

? ? const { appContext } = getCurrentInstance() as ComponentInternalInstance

? ? const globalProperties = appContext.config.globalProperties

? ? return {

? ? ? ? globalProperties

? ? }

}

組件中使用

// 先引入文件
import useCurrentInstance from "@/hooks/useCurrentInstance";

...// 在setup 中使用處理
const { globalProperties } = useCurrentInstance();

二.不能使用getCurrentInstance的ctx

我們?cè)讷@取Vue3中全局掛載的方法時(shí)會(huì)這么寫:

這里的ctx不是setup提供的ctx

const { ctx } = getCurrentInstance()

這里ctx打包后在生產(chǎn)環(huán)境下是獲取不到的,請(qǐng)各位沒(méi)玩過(guò)生產(chǎn)的別不小心誤導(dǎo)到別人啊哈,恰好在Vue3的issues中找到的。

正確應(yīng)該使用

const { proxy } = getCurrentInstance()

總結(jié)

到此這篇關(guān)于Vue3+ts+setup getCurrentInstance使用時(shí)遇到問(wèn)題以及解決的文章就介紹到這了,更多相關(guān)Vue3 ts setup getCurrentInstance使用問(wèn)題內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論