简体   繁体   English

如何操作接收到的 svg(访问 &#39;<g> &#39; 和 &#39;<rect> &#39; 元素)通过 vue

[英]How to manipulate a received svg (access '<g>' and '<rect>' elements) via vue

I'm getting several SVG's that are all structured like this:我得到了几个结构如下的 SVG:

<?xml version="1.0" encoding="utf-8"?>
<svg>
    ...
    <g id="cabin">
        <g id="1">
            <g id="a">
                <rect />
                <path />
            </g>
            <g id="b">
                <rect />
                <path />
            </g>
        </g>
        <g id="2">
            <g id="a">
                <rect />
                <path />
            </g>
            <g id="b">
                <rect />
                <path />
            </g>
        </g>
        ...
    </g>
</svg>

I'm loading the SVG via the html-loader我正在通过html-loader SVG

<div ref="plan" v-html="require('!html-loader!../assets/plaene/plan_1.svg')"></div>

I'm trying to access all child notes of cabin to change the style of the rect items.我正在尝试访问cabin所有子注释以更改rect项目的style How should I do this?我该怎么做? I tried this before in a single html -file with plain javascript我之前在一个带有纯javascript html文件中尝试过这个

var plan = document.getElementById("plan");
plan.addEventListener("load",function() {
    dom = plan.contentDocument;
    let cabins = dom.getElementById('cabin');
    ...
    and so on

but I don't know how to do this in vue .但我不知道如何在vue做到这一点。 I have read some articles (eg VueJS — Tips & Best Practices ) which say that you shold avoid manipulating the DOM directly , so I guess there must be something else.我读过一些文章(例如VueJS — Tips & Best Practices ),这些文章说你应该避免直接操作 DOM ,所以我想肯定还有别的东西。

Has somebody a solution for this?有人对此有解决方案吗? Thank you in advance!先感谢您!

I ended up doing this:我最终这样做了:

let numbers = [1, 2]
let g_tags = this.$el.getElementsByTagName('g')

let svg_root
g_tags.forEach(el => {
    if(el.getAttribute('id') === 'cabin') {
        svg_root = el
    }
})

svg_root.children.forEach(obj => {
     let id = obj.getAttribute('id')

     if (numbers.includes(parseInt(id))) {
         obj.firstElementChild.firstElementChild.setAttribute("style", "fill: green")
         obj.lastElementChild.firstElementChild.setAttribute("style", "fill: green")  
     }
})

I guess by using this.$el I access the virtual and not the real DOM , so it should be "legal".我想通过使用this.$el我访问虚拟而不是真实的DOM ,所以它应该是“合法的”。 Please let me know if I'm wrong and there is a better solution.如果我错了,请告诉我,有更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM