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

Vue3+ts+setup?getCurrentInstance使用時遇到的問題以及解決辦法

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

環(huán)境

vscode
typescript4
vue3

問題描述

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

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會報
// 類型“ComponentInternalInstance | null”上不存在屬性“proxy”。ts(2339)
const { proxy } = getCurrentInstance()

// 然后下面會報這個錯誤
// 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('')

以上就是報錯的全部內(nèi)容,接下來我們解決這個問題

問題解決

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

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

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

這個解決起來更簡單了,在proxy后面添加?來過濾null的結(jié)果

proxy?.$axios('')

以上,問題解決!

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

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

報錯:...類型“ComponentInternalInstance | null”

就嗝屁了。。。

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

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

但是這個方法很無腦,也麻煩。。。

2. 考慮到在獲取上下文和全局掛載實(shí)例的時候會用到這個getCurrentInstance,那我們來新建 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

我們在獲取Vue3中全局掛載的方法時會這么寫:

這里的ctx不是setup提供的ctx

const { ctx } = getCurrentInstance()

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

正確應(yīng)該使用

const { proxy } = getCurrentInstance()

總結(jié)

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

相關(guān)文章

最新評論