在vue2时代,$refs 直接操作子组件

this.$refs.gridlayout.$children[index];

虽然不推荐这么做,但是确实非常好用。但是vue2快速迁移到vue3,之前的这个写法因为干进度,不想重构,直接搬迁,发现不行?

看了下官方的文档:https://v3.cn.vuejs.org/guide/migration/array-refs.html#%E8%BF%81%E7%A7%BB%E7%AD%96%E7%95%A5

<template>
    <div v-for="item in list" :ref="setItemRef"></div>
</template>
<script setup>
    let itemRefs = ref()
    const setItemRef = el => {
      if (el) {
        itemRefs.push(el)
      }
    }
    onBeforeUpdate(() => {
      itemRefs = []
    })
    onUpdated(() => {
      console.log(itemRefs)
    })
</script>

注意:

  • itemRefs 不必是数组:它也可以是一个对象,其 ref 可以通过迭代的 key 被设置

  • 如有需要,itemRefs 也可以是响应式的,且可以被侦听。

在tsx 这个怎么弄呢?

TSX refs

网上的大部分教程都是 template 的

Typing Template Refs

const el = ref<HTMLInputElement | null>(null)

普通元素

Typing Component Template Refs

import MyModal from './MyModal.vue'

const modal = ref<InstanceType<typeof MyModal> | null>(null)

const openModal = () => {
  modal.value?.open()
}

对于子组件,其实和 let timer: ReturnType<typeof setTimeout> = null; 类似。

如果不进行类型声明,modal 方法无法调用。 需要是as  魔法了

还有一个需要特别注意,就是子组件内容是暴露出来的,如果是 <script setup> 组件,是无法获取内容的,具体参看:

vue2升级vue3:单文件组件概述 及 defineExpos/expose https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8872.html

Refs 获取子元素,并操作子元素

import { defineComponent, nextTick, onBeforeUpdate, onMounted, onUnmounted, ref } from 'vue';
import ChartWrapper from '@/components/chart-wrapper';
import props from './props';
import { AddChartType, PanelModel, IGridPos } from '@/typings'; import { DashboardModule, sortGridPanels } from '@modules/dashboard';
import { getPluginTypes, handleInitChartPlugin, handleInitDataSource } from '@/utils/dashboard';
import Loading from '@/components/loading';
import { GRID_COL_NUM, GRID_ROW_HEIGHT, GRID_ROW_MARGIN, initPanel } from '@/constants';
import { debounce } from 'lodash';
import { deepClone } from '@/utils';
import AddPanel from '@dashboard/grid-panel/add-panel';
import TabPanel from '@dashboard/tab-panel/index';
import { GridItem, GridLayout } from 'v3-grid-layout';
import 'v3-grid-layout/dist/style.css';
import './index.scss';
import Row from './Row';
import EventBus from '@/utils/eventBus'; export default defineComponent({
  name: 'GridPanelPlugin',
  props,
  emits: ['ready', 'delete', 'mounted'],
  setup(props, { emit }) {
    const layout = ref<IGridPos[]>([]);
    const gridLayout = ref<InstanceType<typeof GridLayout>>(null);
    const gridItem = ref<InstanceType<typeof GridItem>[]>([]);
    const dashboardPanel = ref<Element>(null);
    onBeforeUpdate(() => {
      gridItem.value = [];
    });
    function drag(e: DragEvent) {
      const parentRect = dashboardPanel.value.getBoundingClientRect();
      let mouseInGrid = false;
      if (
        ((mouseXY.x > parentRect.left) && (mouseXY.x < parentRect.right))
        && ((mouseXY.y > parentRect.top) && (mouseXY.y < parentRect.bottom))) {
        mouseInGrid = true;
      }
      if (mouseInGrid === true && (layout.value.findIndex(item => item.i === 'drop')) === -1) {
        layout.value.push({
          x: (layout.value.length * 2) % (GRID_COL_NUM || 12),
          y: layout.value.length + (GRID_COL_NUM || 12), // puts it at the bottom
          w: 1,
          h: 1,
          i: 'drop',
        });
      }
      const index = layout.value.findIndex(item => item.i === 'drop');
      if (index !== -1) {
        const el = gridItem.value[index];
        el.dragging.data = { top: mouseXY.y - parentRect.top, left: mouseXY.x - parentRect.left };
        const new_pos = el.calcXY(mouseXY.y - parentRect.top, mouseXY.x - parentRect.left);
        if (mouseInGrid === true) {
          gridLayout.value.dragEvent('dragstart', 'drop', new_pos.x, new_pos.y, 1, 1);
          DragPos.i = String(index);
          DragPos.x = layout.value[index].x;
          DragPos.y = layout.value[index].y;
        }
        if (mouseInGrid === false) {
          gridLayout.value.dragEvent('dragend', 'drop', new_pos.x, new_pos.y, 1, 1);
          layout.value = layout.value.filter(obj => obj.i !== 'drop');
        }
      }
    }     function dragend(e: DragEvent) {
      // const parentRect = document.getElementById('dashboard-panel').getBoundingClientRect();
      const parentRect = dashboardPanel.value.getBoundingClientRect();
      let mouseInGrid = false;
      if (((mouseXY.x > parentRect.left) && (mouseXY.x < parentRect.right))
        && ((mouseXY.y > parentRect.top) && (mouseXY.y < parentRect.bottom))) {
        mouseInGrid = true;
      }
      if (mouseInGrid === true) {
        gridLayout.value.dragEvent('dragend', 'drop', DragPos.x, DragPos.y, 1, 1);
        layout.value = layout.value.filter(obj => obj.i !== 'drop');
        // UNCOMMENT below if you want to add a grid-item
        this.layout.push({
            x: DragPos.x,
            y: DragPos.y,
            w: 1,
            h: 1,
            i: DragPos.i,
        });
        this.$refs.gridLayout.dragEvent('dragend', DragPos.i, DragPos.x,DragPos.y,1,1);
        try {
            this.$refs.gridLayout.$children[this.layout.length].$refs.item.style.display="block";
        } catch {
        }
      }
    }     return {
      gridLayout,
      gridItem,
      dashboardPanel,
      layout,
      movedId,
      inited,
      isLayoutReady,
      isShowEditRowDialog,
      rowForm,
    };
  },
  render() {
    if (!this.inited) {
      return (<Loading/>);
    }
    return (
      <div
        ref='dashboardPanel'
        id='dashboard-panel'
        class={'dashboard-panel flex-1'}>
        <GridLayout
          ref='gridLayout'
          layout={this.layout}
          col-num={GRID_COL_NUM}
          row-height={GRID_ROW_HEIGHT}
          is-resizabl={this.editable}
          is-draggable={this.editable}
          vertical-compact={true}
          use-css-transforms={false}
          margin={GRID_ROW_MARGIN}
          on-layout-updated={this.handleLayoutUpdated}
          on-layout-ready={this.onLayoutReady}
        >
          {
            this.layout.map((item) => {
              return (
                <GridItem
                  ref={(el: any) => {
                    if (el) {
                      this.gridItem.push(el);
                    }
                  }}
                  {{...item}}
                 >
                  {chart}
                </GridItem>
              );
            })
          }
        </GridLayout>
      </div>
    );
  },
});

当然,这个代码是抽离出来的。

这个vue3-grid-layout,自己写了弄了一版,https://github.com/zhoulujun/vue3-grid-layout

转载本站文章《vue2升级vue3: TSX Vue 3 Composition API Refs》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8873.html

vue2升级vue3: TSX Vue 3 Composition API Refs的更多相关文章

  1. vue2升级vue3:Vue Demij打通vue2与vue3壁垒,构建通用组件

    如果你的vue2代码之前是使用vue-class-component 类组件模式写的.选择可以使用 https://github.com/facing-dev/vue-facing-decorator ...

  2. vue2升级vue3:vue2 vue-i18n 升级到vue3搭配VueI18n v9

    项目从vue2 升级vue3,VueI18n需要做适当的调整.主要是Vue I18n v8.x 到Vue I18n v9 or later 的变化,其中初始化: 具体可以参看:https://vue- ...

  3. vue2升级vue3指南(二)—— 语法warning&error篇

    本文总结了vue2升级vue3可能会遇到的语法警告和错误,如果想知道怎样升级,可以查看我的上一篇文章:vue2升级vue3指南(一)-- 环境准备和构建篇 Warning 1.deep /deep/和 ...

  4. vue2升级vue3:vue-i18n国际化异步按需加载

    vue2异步加载之前说过,vue3还是之前的方法,只是把 i18n.setLocaleMessage改为i18n.global.setLocaleMessage 但是本文还是详细说一遍: 为什么需要异 ...

  5. uniapp项目vue2升级vue3简单记录

    看到好多开源项目都升级了vue3,看文章说vue3性能升级很多,而且组合式api很香,遂把最近开发的自助洗车app升级下,在此记录下出现的问题. uniapp升级vue3官方指南 我是先去vue官网看 ...

  6. 蒲公英 &#183; JELLY技术周刊 Vol.21 -- 技术周刊 &#183; React Hooks vs Vue 3 + Composition API

    蒲公英 · JELLY技术周刊 Vol.21 选 React 还是 Vue,每个人心中都会有自己的答案,有很多理由去 pick 心水的框架,但是当我们扪心自问,我们真的可以公正的来评价这两者之间的差异 ...

  7. vue2升级vue3指南(一)—— 环境准备和构建篇

    1.nodejs和npm 注意二者的版本,版本过低需要升级,本人升级后的版本如下: $ node -v v16.15.1 $ npm -v 8.11.0 2.package.json 和依赖升级 由于 ...

  8. Vue3:不常用的Composition API && Fragment、Teleport、Suspense && 与Vue2对比的一些变化

    1 # 一.Vue3不常用的Composition API 2 # 1.shallowReactive与shallowRef 3 .shallowReactive: 只处理对象最外层属性的响应式(浅响 ...

  9. Vue2 到 Vue3,重温这 5 个常用的 API

    距离Vue3发布已经过去一年多时间了,从Vue2到Vue3是一个不小的升级,包括周边生态等.虽然目前大多数开发者们在使用的仍旧以Vue2为准,但Vue3显然是Vue开发者们未来必须面对的,而且前不久V ...

  10. 了解 Vue 的 Compsition API

    在这篇文章中,我将讲讲 Vue 的 Composition API 为什么比之前的 Options API 要好,以及它是如何工作的. Options API 有什么问题 首先,这里不是要大家放弃 O ...

随机推荐

  1. Isito 入门(八):金丝雀发布

    本教程已加入 Istio 系列:https://istio.whuanle.cn 目录 6,金丝雀发布 金丝雀发布 按照流量比例划分 按照 Header 划分 6,金丝雀发布 项目总是处于不断变化之中 ...

  2. 实时计算Flink+实时数仓Hologres

    阿里云培训:https://developer.aliyun.com/learning/course/807/detail/13885?accounttraceid=d2070f0a9edb471c9 ...

  3. AtCoder Beginner Contest 326 (ABC326)

    A. 2UP3DOWN 直接模拟即可. Code B. 326-like Numbers 枚举,每次拆除百.十.个位,再判断. Code C. Peak Description 数字线上放置了 \(N ...

  4. [Python] Turtle库的运用, 创作精美绘画

    更多示例代码下载地址 : https://github.com/Amd794/Python123 前言 最初来自于 Wally Feurzig 和 Seymour Papert 于 1966 年所创造 ...

  5. 2022.7.13 tongyf 讲课纪要

    前言 这个笔记记晚了,主要是都在跟 \(LCT\) 进行殊死搏斗,所以博客这方面就挂了很久. tongyf 学长当年是拿到省一之后省选炸了,之后暴切高考.ORZ%%% 这节课讲的是线性dp和背包dp, ...

  6. 递归与分治思想:治思想 && 折半查找法(迭代 && 递归)

    1 //分治思想:将大问题拆成小问题逐一解决 2 //折半查找法:不断缩小一半查找的范围,知道达到目的,效率较高. 详情见:https://fishc.com.cn/thread-27964-1-1. ...

  7. dfs:马踏棋盘

    1 #include<stdio.h> 2 #include<time.h> 3 4 #define X 8 5 #define Y 8 6 7 int chess[X][Y] ...

  8. 一个简单案例的Vue2.0源码

    本文学习vue2.0源码,主要从new Vue()时发生了什么和页面的响应式更新2个维度了解Vue.js的原理.以一个简单的vue代码为例,介绍了这个代码编译运行的流程,在流程中原始DOM的信息会被解 ...

  9. logstash 配置文件语法介绍

    大家好,我是蓝胖子,之前在构建服务监控实践那个系列里,有提到用logstash来做日志的收集,但是对于logstash的配置文件语法没有做很详细的介绍,今天就来详细聊聊logstash配置文件的语法. ...

  10. 【matlab混沌理论】1.1.混沌理论简介

    混沌理论 1.简介          混沌理论是一个跨学科的科学研究领域和数学分支,专注于对初始条件高度敏感的动力系统的基本模式和确定性定律,曾被认为具有完全随机的无序和不规则状态.混沌理论指出,在混 ...