关于vue3 解决getCurrentInstance 打包后线上环境报错问题
作者:船长在船上
这篇文章主要介绍了vue3 解决getCurrentInstance 打包后线上环境报错问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
getCurrentInstance
getCurrentInstance 支持访问内部组件实例。
WARNING
getCurrentInstance只暴露给高阶使用场景,典型的比如在库中。强烈反对在应用的代码中使用getCurrentInstance。请不要把它当作在组合式 API 中获取this的替代方案来使用。
import { getCurrentInstance } from 'vue'
const MyComponent = {
setup() {
const internalInstance = getCurrentInstance()
internalInstance.appContext.config.globalProperties // 访问 globalProperties
}
}打印信息:

getCurrentInstance 只能在setup或生命周期钩子中调用。
如需在 setup或生命周期钩子外使用,请先在
setup中调用getCurrentInstance()获取该实例然后再使用。
setup() {
const internalInstance = getCurrentInstance() // 有效
const id = useComponentId() // 有效
const handleClick = () => {
getCurrentInstance() // 无效
useComponentId() // 无效
internalInstance // 有效
}
}本地使用示例:
当前在本地使用没有问题,线上环境会报错,不建议使用
<script>
import {getCurrentInstance} from "vue";
export default {
components: {
},
setup() {
const {ctx} = getCurrentInstance();
console.log(ctx,"属性1")
}
</script>查看打印:

项目中使用:表单table列表查询

方法1: 不推荐
setup() {
const {ctx} = getCurrentInstance();
console.log(ctx,"属性1")
//表单查询方法
const submitForm = (formName) =>{
ctx.$refs[formName].validate(valid => {
if (valid) {
ruleForm.pageNum = 1;
getTableData();
} else {
console.log("error submit!!");
return false;
}
});
}
}方法2:推荐此用法,才能在你项目正式上线版本正常运行,避免线上报错问题
解决:用proxy代替ctx。在结构的时候直接将proxy解构出来
setup() {
let {proxy} = getCurrentInstance();
console.log(proxy,"属性2");
//表单查询方法
const submitForm = (formName) =>{
proxy.$refs[formName].validate(valid => {
if (valid) {
ruleForm.pageNum = 1;
getTableData();
} else {
console.log("error submit!!");
return false;
}
});
}
}打印:

到此这篇关于vue3 解决getCurrentInstance 打包后线上环境报错问题的文章就介绍到这了,更多相关vue3 getCurrentInstance 打包报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
- vue打包报错:ERROR in static/js/xxx.js from UglifyJs undefined问题
- 用electron打包vue项目中的报错问题及解决
- 解决vue打包报错Unexpected token: punc的问题
- vue打包静态资源后显示空白及static文件路径报错的解决
- vue打包npm run build时候界面报错的解决
- vue 解决uglifyjs-webpack-plugin打包出现报错的问题
- 解决vue打包后刷新页面报错:Unexpected token <
- vue-cli 打包后提交到线上出现 "Uncaught SyntaxError:Unexpected token" 报错
- 打包组件报错:Error:Cannot find module 'vue/compiler-sfc'
