【发布时间】:2019-03-29 22:30:30
【问题描述】:
我将一组图像 url 作为 props 传递给我的 Konva 组件,为每个 url 创建一个图像对象,将该对象存储在一个数据对象中(使用 Vue 的 $set 方法来保持对象文字的反应性),然后使用v-for 为我的数据对象中的每个图像对象创建一个v-image。这似乎工作正常,但是我遇到了一个问题,如果我尝试删除其中一个图像,则会删除 2 个图像。仅当我尝试删除的图像不是最上面的图像时才会发生这种情况。在控制台中,我收到警告 Konva warning: Node has no parent. zIndex parameter is ignored.。我的预感是,这是因为 konva 的 destroy 方法与 vue 的 $delete 方法在 v-for 中使用的数据对象上发生冲突。我已经为此奋斗了几个小时,如果我能得到任何帮助,我将不胜感激。相关代码如下。谢谢!
父母
<template>
<editor ref="editor" :image-props.sync="images"/>
<button @click="remove">remove</button>
</template>
export default {
components: {
Editor,
},
data() {
return {
images: [url1, url2, etc...],
};
},
methods: {
remove() {
this.$refs.editor.removeSelectedImage();
},
}
孩子
<template>
<div>
<v-stage>
<v-layer>
<v-group>
<v-image v-for="image in Object.values(images)"
:key="image.id" :config="image"/>
</v-group>
</v-layer>
</v-stage>
</div>
</template>
export default {
props: {
imageProps: Array,
},
data() {
return {
images: {},
selectedNode: null //this gets updated on click
},
watch: {
imageProps() {
this.registerImages();
},
mounted() {
this.registerImages();
},
methods: {
registerImages() {
this.imageProps.forEach(url => {
if (!this.images[url]) {
let img = new Image();
img.src = url;
img.onload = () => {
this.$set(this.images, url, {
image: img,
draggable: true,
name: url,
x: 0,
y: 0,
});
}
}
});
},
removeSelectedLayer() {
let newImageProps = this.imageProps.filter(url => url !== this.selectedImageName);
this.$emit('update:image-props', newImageProps);
this.selectedNode.destroy();
this.$delete(this.images, this.selectedImageName);
this.stageArea.draw();
},
如果我在 Vue devtools 中检查组件,images 对象看起来和 imageProps 一样正确(即使 Vue DOM 树看起来正确,v-images 的数量也正确)但是画布显示少 1图像比它应该。同样,仅当我删除最初不在顶部的图像时才会发生这种情况。如果我删除最上面的图像,它似乎可以正常工作。
【问题讨论】:
-
你能做一个在线演示吗?但基本上,您不应该从画布中手动删除节点。相反,只需从
data中的数组中删除一个项目。 -
抱歉延迟回复。这是一个快速演示:codesandbox.io/embed/nkv4908mx4。请注意,如果您没有选择最顶层,它将删除多个图层
-
另外请注意,如果您注释掉
destroy()调用,它将删除正确的节点,但从顶部节点开始的第二个节点将捕捉到已删除节点的位置。