【问题标题】:Vue3 and Typescript error: Property '$el' does not exist on type 'void'. How to properly grab every tag type existing in DOM?Vue3 和 Typescript 错误:“void”类型上不存在属性“$el”。如何正确抓取 DOM 中存在的每个标签类型?
【发布时间】:2022-07-09 07:25:43
【问题描述】:

我正在将 Vue2 项目转换为 Vue3 和 Typscript。有很多奇怪的错误,但我不知道如何在$el 上处理这个错误。

我只是想抓取上面模板中的每个<g> 标签,我可以,但是这个错误仍然存​​在。

关于如何解决这个问题的任何想法?

这里是组件的模板,但是整个组件太大放不上stackoverflow。我需要定位<g>标签。

<template>
  <div class="pep-header-decoration-light">
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="1158.942"
      height="143.376"
      viewBox="0 0 1158.942 143.376"
    >
      <g :style="`color: ${colors.green}`">
        <!-- ... -->
      </g>
      <!-- many more g elements to select here too -->
    </svg>
  </div>
</template>

【问题讨论】:

  • 暗示this 的骗子,其中谈到故意缺少$el。也要小心使用this:箭头函数没有自己的this,setup 中的this 是null,如in the tip here 所列。
  • @JeffBowman 谢谢你的回答。我确实看到了 ref 的使用,但我的模板需要所有 标签,其中有很多。我真的需要在每个 标签上添加一个模板引用吗?好像有点过分了
  • 您没有向我们展示模板,如果有 SVG 元素,您可以在其上设置 ref 并从那里执行 querySelectorAll 或其他 DOM 遍历。您不能特别依赖 this 或 $el 在您的 setup 中。
  • 我已将大部分反馈转换为答案。我将编辑与您的问题无关的部分;以后,请不要上传您的代码截图,而是复制粘贴文本,以便于阅读和修改。干杯!

标签: typescript vue.js vuejs3


【解决方案1】:

与问题Vue 3 Composition API - How to get the component element ($el) on which component is mounted 一样,Vue 3 不鼓励使用$el,因为组件可以有多个顶级元素。此外,your arrow function won't redefine this 和 this is not available in setup:

setup() 本身无权访问组件实例 - this 在setup() 中的值将是null。您可以从 Options API 访问 Composition-API 公开的值,但反之则不行。

鉴于此,您可能应该为封闭的div 或封闭的svg 定义一个ref,并使用它来访问您的元素:

<template>
  <div class="pep-header-decoration-light" ref="divEl">
    <svg [...]>
      <!-- ... -->
    </svg>
  </div>
</template>

请注意,您需要在 setup 返回的对象中返回新的 ref,并在模板中返回 it needs the same name。您可以稍后使用this.$refs.divEl 访问它,但在setup 函数中,您无权访问this 来访问this.$refs。

setup(props) {
  const divEl = ref<HTMLDivElement>(); // create the ref here
  onMounted(() => {
    // no `this` and no `$el`, so use `divEl.value`
    const shapes = divEl.value.querySelectorAll("svg > g");
    // ...
  });
  // ...
  return {divEl}; // exposes the ref named `divEl`, and since it matches
                  // the template, vue will populate it during mount
}

【讨论】:

  • 我没有找到DivElement,正确的名字应该是Element或者HTMLDivElement
  • 没错,是凭记忆写的。固定。
猜你喜欢
  • 2022-06-22
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 2019-04-12
  • 2020-07-09
  • 2019-10-20
相关资源
最近更新 更多