getCurrentInstance getCurrentInstance 支持访问内部组件实例。 WARNING 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 打包报错内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 关于vue3 解决getCurrentInstance 打包后线上环境报错问题
本文链接: https://www.lsjlt.com/news/149608.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0