javascript - 将子项附加到 SVG 对象不会更新 Vue 中的 SVG

标签 javascript vue.js svg

我有一个 SVG 对象,当我单击它时,我希望在那里出现一个矩形。我可以让它在 Vue 之外工作,但不能使用 Vue。

Vue 中的 HTML/模板字符串

<svg id="mysvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="1285 579 475 220" preserveAspectRatio="xMidYMid meet">
<image width="2111" height="1219" xlink:href="./hogviltsgatan.png"></image>
  <g id="local" transform="scale(4)">
    <rect x="50" y="50" width="100" height="100" rx="10" />
  </g>

</svg>
<p id="coords">co-ordinates</p>

Vue 方法:

handleMouseClick(e) {
  var
    t = e.target,
    x = e.clientX,
    y = e.clientY,
    target = (t == this.svg ? this.svg : t.parentNode),
    svgP = this.svgPoint(target, x, y),
    rect = this.createRect(this.NS, svgP.x ,svgP.y, 50, 50);
    target.appendChild(rect);
}


svgPoint(element, x, y){
  let pt = this.svg.createSVGPoint();
  pt.x = x;
  pt.y = y;
  return pt.matrixTransform(element.getScreenCTM().inverse());
},

createRect (svg, x,y, height, width){
  let rect = document.createElementNS(this.svg, 'rect');
    rect.setAttributeNS(null, 'x', x);
    rect.setAttributeNS(null, 'y', y);
    rect.setAttributeNS(null, 'height', '75');
    rect.setAttributeNS(null, 'width', '50');
    // rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
    return rect;
},

  created() {

    .
    .
    this.svg = document.getElementById('mysvg'),
    this.NS = this.svg.getAttribute('xmlns'),
    this.local = this.svg.getElementById('local'),
    this.coords = document.getElementById('coords');
    .
    .

如果我将 target 打印到控制台,我可以看到矩形已被附加。但是,它没有出现在我的浏览器中。 svgPoint 和 createRect 方法有效。同样,该代码在 Vue 之外运行良好。看来 Vue 没有更新。如果我在模板字符串中硬编码一个矩形,它显示得很好。

最佳答案

使用 rects 的数据创建和操作对象数组

https://jsfiddle.net/53o2fxk6/2/

rects : [
   {id: 'id1', x:10, y:10, w:20, h:20},
   {id: 'id2', x:10, y:10, w:20, h:20},
   {id: 'id3', x:10, y:10, w:20, h:20},
   {id: 'id4', x:10, y:10, w:20, h:20}
]

操纵物体

createRect: function(_id, _x, _y, _w, _h) {
    this.rects.push({id:_id, x:_x, y:_y, w:_w, h:_h});
}

使用 vue 方法创建 SVG

<svg>
    <g v-for="rect in rects" :id="rect.id" />
        <rect :x="rect.x" :y="rect.x" :width="rect.w" :height="rect.h">
    </g>
</svg>

关于javascript - 将子项附加到 SVG 对象不会更新 Vue 中的 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037560/

相关文章:

JavaScript fancybox "conflict wrapper"代码,它是如何工作的?

javascript - 如何在 React 中动态创建新的全局 css 类?

javascript - 绑定(bind)类的 Vue 条件

vue.js - 防止 Vue 组件内的路由更改

html - CSS:加载 SVG 和相对于其元素的位置

javascript - 从对象即数据创建多个元素

javascript - 使用递归获取嵌套对象中的所有父对象

javascript - Vue.js - 如何在 html 页面中打印包含换行符的字符串变量(从过滤器返回)

css - 如何为 SVG <image> 元素设置背景颜色

svg - 增加 D3 图中边缘的可点击区域