我正在將 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>
uj5u.com熱心網友回復:
正如問題Vue 3 Composition API - How to get the component element ($el) on which component ismounted一樣,Vue 3 不鼓勵使用$el,因為組件可以有多個頂級元素。此外,您的箭頭函式不會重新定義this,并且this在 中不可用setup:
setup()本身無權訪問組件實體 -this將具有nullinside的值setup()。您可以從 Options API 訪問 Composition-API 公開的值,但反之則不行。
鑒于此,您可能應該ref為您的封閉div或封閉定義 a svg,并使用它來獲取您的元素:
<template>
<div class="pep-header-decoration-light" ref="divEl">
<svg [...]>
<!-- ... -->
</svg>
</div>
</template>
請注意,您需要在回傳ref的物件中setup回傳 new,并且它需要與模板中的名稱相同。您可以稍后使用 訪問它this.$refs.divEl,但在setup您無權訪問的功能中this訪問this.$refs。
setup(props) {
const divEl = ref<DivElement>(); // 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/438561.html
上一篇:如何使用樹莓派啟動vue服務器?
