Vue3使用$refs获取节点生产环境undefined-使用getCurrentInstance-ctx应改用proxy

news2024/10/7 10:24:21

  

vue3项目,在使用refs获取节点,开发环境正常,生产环境报错

console.log(getCurrentInstance())

internalInstance.ctx,

internalInstance.proxy

开发环境正常-生产环境报错

 internalInstance.ctx

生产环境获取不到值

ctx打包后在生产环境下是获取不到

<script setup>
import {
  defineProps,
  getCurrentInstance,
  reactive,
  ref,
  nextTick,
  onMounted,
} from "vue";

let internalInstance = "";

onMounted(() => {
  internalInstance = getCurrentInstance();
  // { proxy } = getCurrentInstance()
  console.log(
    "internalInstance",
    internalInstance,
    internalInstance.ctx,
    internalInstance.proxy
  );
});


let nums = reactive(["", "", "", "", "", ""]);


// nextTick(() => {
//   // input0.value.focus();
//   currentInput.value++;
//   // console.log(["input" + currentInput.value].value, "123");
//   // console.log(input0.value.value);
// });

let activeIndex = 0;

const onKeyDown = (index, e) => {
  // console.log(index, e, activeIndex, 888);
  switch (e.keyCode) {
    case 8: // backspace键
      e.preventDefault();
      if (nums[index]) {
        nums[index] = "";
        if (index > 0) {
          nextTick(() => {
            activeIndex = index - 1;
            const prevInput = internalInstance.ctx.$refs[`input${index - 1}`];
            console.log("prevInput", prevInput);
            prevInput.focus();
          });
        }
      } else if (index === 0) {
        activeIndex = 0;
      }
      break;
    default:
      break;
  }
};

const handleInput = (index) => {
  // console.log(index, activeIndex, 999);
  if (nums[index]) {
    activeIndex = index;
    if (index < 5) {
      nextTick(() => {
        const nextInput = internalInstance.ctx.$refs[`input${index + 1}`];
        console.log("nextInput", nextInput);
        nextInput.focus();
      });
    }
  }
};
</script>

修复bug

将internalInstance.ctx

替换成 internalInstance.appContext.config.globalProperties或者internalInstance.proxy

<script setup>
import {
  defineProps,
  getCurrentInstance,
  reactive,
  ref,
  nextTick,
  onMounted,
} from "vue";

let internalInstance = "";

onMounted(() => {
  internalInstance = getCurrentInstance();
  // { proxy } = getCurrentInstance()
  console.log(
    "internalInstance",
    internalInstance,
    internalInstance.ctx,
    internalInstance.proxy
  );
});


let nums = reactive(["", "", "", "", "", ""]);


// nextTick(() => {
//   // input0.value.focus();
//   currentInput.value++;
//   // console.log(["input" + currentInput.value].value, "123");
//   // console.log(input0.value.value);
// });

let activeIndex = 0;

const onKeyDown = (index, e) => {
  // console.log(index, e, activeIndex, 888);
  switch (e.keyCode) {
    case 8: // backspace键
      e.preventDefault();
      if (nums[index]) {
        nums[index] = "";
        if (index > 0) {
          nextTick(() => {
            activeIndex = index - 1;
            const prevInput = internalInstance.proxy.$refs[`input${index - 1}`];
            console.log("prevInput", prevInput);
            prevInput.focus();
          });
        }
      } else if (index === 0) {
        activeIndex = 0;
      }
      break;
    default:
      break;
  }
};

const handleInput = (index) => {
  // console.log(index, activeIndex, 999);
  if (nums[index]) {
    activeIndex = index;
    if (index < 5) {
      nextTick(() => {
        const nextInput = internalInstance.proxy.$refs[`input${index + 1}`];
        console.log("nextInput", nextInput);
        nextInput.focus();
      });
    }
  }
};
</script>

在获取上下文和全局挂载实例的时候会用到这个getCurrentInstance,那我们来新建 hooksuseCurrentInstance.ts 

import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export default function useCurrentInstance() {
    const { appContext } = getCurrentInstance() as ComponentInternalInstance
    const globalProperties = appContext.config.globalProperties
    return {
        globalProperties
    }
}



// 先引入文件
import useCurrentInstance from "@/hooks/useCurrentInstance";
...
// 在setup 中使用处理
const { globalProperties } = useCurrentInstance();

defineExpose 

<script setup>
import { ref } from '@vue/reactivity';

let message = ref('子元素').value

const alertMessage = function () {
    alert(message)
}

defineExpose({
    message,
    alertMessage
})
</script>

通过<script setup>语法糖的写法,其组件是默认关闭的,也就是说如果是通过$refs或者$parents来访问子组件中定义的值是拿不到的,必须通过defineExpose向外暴露你想获取的值才行

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/717815.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

激光SLAM(一):点云基础知识

点云基础知识 一、激光雷达介绍1. 机械旋转式雷达2. 固态雷达 二、测量模型与点云1. Range-Azimuth-Elevation&#xff08;RAE&#xff09;- XYZ2. 点云的Packets表示3. 点云的鸟瞰图表示4.Range Image5.TSDF 三、点云的近邻关系Brute-force KNN栅格、体素KD-tree寻找近邻四叉树…

Visual Studio Code系列--CMake Tools使用说明

一、目的 在linux系统上开发程序&#xff0c;一般都是使用vimgccgdb进行的&#xff1b;但是为了开发效率我们也会使用Visual Studio Code进行开发&#xff0c;毕竟有界面的开发调试还是更加友好一些。 老牌程序员肯定都知道make构建工具&#xff0c;但是其晦涩的语法还是难住不…

二十一、数值操作(二)

目录 七、数值查找 1、Excel实现 2、Python实现 八、区间切分 1、Excel实现 2、Python实现 九、插入新的行或列 1、Excel实现 2、Python实现 十、行列互换 1、Excel实现 2、Python实现 十一、索引重塑 十二、长宽表转换 1、宽表转换为长表 &#xff08;1&#x…

如何提升软件质量及开发效率

如何提升软件质量及开发效率 文章目录 如何提升软件质量及开发效率1、简介2、软件质量模型3、需求分析4、软件设计5、项目管理1.1 版本管理1.2 项目结构规范 6、编码规范7、代码评审8、软件调试9、软件测试 1、简介 保证软件质量&#xff0c;是一个贯穿整个软件生存周期的重要…

Java利用朴素贝叶斯分类算法实现信息分类

目录 贝叶斯分类算法 代码实例 数据集data.txt代码实现输出结果使用场景 贝叶斯分类算法 贝叶斯分类算法是统计学的一种分类方法&#xff0c;它是一类利用概率统计知识进行分类的算法。在许多场合&#xff0c;朴素贝叶斯(Nave Bayes&#xff0c;NB)分类算法可以与决策树和神…

项目管理考核积分指标库大全V3.0

近期热文&#xff1a;大咖来袭&#xff01;中国PMO&PM大会议程隆重发布&#xff0c;三城联动 北京、上海、深圳三地同步进行&#xff0c;两天近70位项目管理大咖专家齐聚一堂&#xff0c;交流分享。各路高手汇聚一处&#xff0c;互相学习。精心的圆桌设计&#xff0c;穿插…

uniapp打包白屏问题

【bug】&#xff1a;浏览器运行正常&#xff0c;模拟器、真机运行只有tab栏显示&#xff0c;或者完全白屏。打包也是白屏。 【控制台报错信息】&#xff1a; 注意&#xff1a;app不支持dom操作 【解决办法】&#xff1a;在main.js里修改 render函数是vue通过js渲染dom结构的…

前端vue入门(纯代码)20

总以为自己还很年轻&#xff0c;却忽略了岁月的脚步&#xff0c;当身边的一道道风景变成了回忆&#xff0c;才忽然发现&#xff0c;风景依然在&#xff0c;而人已非少年。&#xff01;&#xff01;&#xff01; 【22.求和案例--纯Vue版本】 太简单了&#xff0c;直接上代码案…

Squid代理服务器

Squid代理服务器 一、Squid相关知识 1.功能 Squid 主要提供缓存加速、应用层过滤控制的功能。 2.工作机制 1&#xff0e;代替客户机向网站请求数据&#xff0c;从而可以隐藏用户的真实IP地址。 2&#xff0e;将获得的网页数据&#xff08;静态 Web 元素&#xff09;保存到…

js:使用typed.js实现打字动画效果

效果预览 目录 实现方式一: 原生JS实现实现方式二&#xff1a;typed.js实现 实现方式一: 原生JS实现 <div id"code"> 我感到未尝经验的无聊&#xff0c;是自此以后的事。我当初是不知其所以然的&#xff1b; 后来想&#xff0c;凡有一人的主张&#xff0c;得…

高薪offer收割面试题之缓存穿透,击穿,雪崩

缓存穿透&#xff0c;缓存击穿&#xff0c;缓存雪崩是我们在应用缓存时最常碰到的问题&#xff0c;也是面试的热点考点。究竟什么是缓存穿透&#xff0c;缓存击穿&#xff0c;缓存雪崩&#xff0c;如何解决&#xff0c;本文会进行详细的剖析。 缓存穿透 什么是缓存穿透&#…

CUDA和CUDNN安装和版本验证

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、安装二、关键指标1.驱动版本和CUDA版本对应1.最适配版本2.最低支持版本 2.CUDA版本和CUDNN版本对应 三、验证有效性1.驱动验证2.CUDA验证1.nvcc2.sample 3.…

E. Masha-forgetful(dp)

题目&#xff1a;Problem - E - Codeforceshttps://codeforces.com/contest/1624/problem/E 题意&#xff1a; 玛莎认识了一个新朋友&#xff0c;并知道了他的电话号码 s 。电话号码是一个长度为m的字符串&#xff0c;它由从 0-9 组成 。 电话号码可能以 0 开头。 玛莎已经…

花30分钟,用Jenkins部署码云上的SpringBoot项目

本文介绍 jenkins 如何从 gitee 上 clone 项目&#xff0c;然后使用 maven 打包并后台启动。 1.Jenkins 介绍 Jenkins 是一个开源软件项目&#xff0c;是基于 Java 开发的一种持续集成工具&#xff0c;用于监控持续重复的工作&#xff0c;旨在提供一个开放易用的软件平台&…

7月4号作业

实现底层实现三盏灯的控制 head.h #ifndef __HEAD_H__ #define __HEAD_H__#define PHY_LED1_MODER 0X50006000 #define PHY_LED1_ODR 0X50006014#define PHY_RCC 0X50000A28#define PHY_LED2_MODER 0X50007000 #define PHY_LED2_ODR 0X50007014#endif led.c #in…

2023年,第九届WWEC教育者大会隆重回归

2023年第九届WWEC教育者大会将于8月20日至22日在上海举行。本次大会也是时隔两年之后再度重启&#xff0c;是疫情恢复常态化后教育界的首次重要大会。 WWEC教育者大会由宋辉先生发起&#xff0c;嘉家有品主办&#xff0c;君学书院、雁传书文化传媒和有鹏来教育科技联合主办。本…

jdbcTemplate的queryForList报错:Incorrect column count: expected 1, actual 2

jdbcTemplate的queryForList方法有多种传参形式&#xff0c;我们常用的就是这种传class类&#xff0c;参数返回数据&#xff0c;结果报expected 1, actual 2&#xff0c;意思是预期只返回一列&#xff0c;但却返回了2列。这是不合理的&#xff0c;因为返回参数都是List&#xf…

PCL 法向量估计源码学习

一、思路&#xff1a; 二、源码 #ifndef PCL_FEATURES_IMPL_NORMAL_3D_H_ #define PCL_FEATURES_IMPL_NORMAL_3D_H_#include <pcl/features/normal_3d.h>/// template <typename PointInT, typename PointOutT> void pcl::NormalEstimation<PointInT, PointOutT…

【Matlab】智能优化算法_海洋捕食者算法MPA

【Matlab】智能优化算法_海洋捕食者算法MPA 1.背景介绍1.1 布朗运动1.2 莱维运动 2.数学模型2.1 MPA配方2.2 MPA优化场景2.3 涡流形成与FAD效应 3.文件结构4.伪代码5.详细代码及注释5.1 func_plot.m5.2 Get_Functions_details.m5.3 initialization.m5.4 levy.m5.5 main.m5.6 MP…

【H5】文件上传(ajax)

系列文章 【移动设备】iData 50P 技术规格 本文链接&#xff1a;https://blog.csdn.net/youcheng_ge/article/details/130604517 【H5】avalon前端数据双向绑定 本文链接&#xff1a;https://blog.csdn.net/youcheng_ge/article/details/131067187 【H5】安卓自动更新方案&a…