关于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'
相关文章
安装@vue/cli 报错npm WARN deprecated request
这篇文章主要介绍了安装@vue/cli 报错npm WARN deprecated request@2.88.2问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-03-03饿了么UI中el-tree树节点选中高亮的两种常用方式(highlight-current属性)
最近新做的项目有用到Element-UI tree组件,下面这篇文章主要给大家介绍了关于饿了么UI中el-tree树节点选中高亮的两种常用方式(highlight-current属性),文中通过实例代码介绍的非常详细,需要的朋友可以参考下2022-12-12
最新评论