当NewValue是相同的字符串时,如何解雇观察者?
I'm inserting base64 images
into an editor by assigning their base64 string
to reactive object state.image
and pointing a watcher at it.问题是,当我想两次插入相同的图像时,观察者不会发射。
Watcher
:
const renderImage = (editor) => {
const unwatch = watch(() => state.image, () => {
console.log('watcher fires!')
editor.chain().focus().setImage({ src: state.image }).run()
unwatch()
state.image = null
})
}
您可以看到我试图用 untatch()
杀死观察者,并另外set set state.image = null
,但加载相同的图像时仍不会发射。
@click
事件在此元素中触发:
<button @click="$refs.image.click(); renderImage(editor)"></button>
<input type="file" ref="image" style="display: none" @change="getImageUrl">
图像的 dataUrl
均在 getimageurl
中创建:
const getImageUrl = (event) => {
const files = event.target.files;
if (!files.length)
return;
const reader = new FileReader();
reader.onload = (event) => {
state.image = event.target.result;
};
reader.readAsDataURL(files[0]);
}
这两个元素似乎都可以根据需要工作。
我该如何使观察者开火?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题假设
观看
回调不是发射的,但是在这种情况下,实际上是&lt; input&gt;
没有发射事件。&lt; input&gt;
仅触发更改
/输入
事件的值实际上更改。选择同一文件时,该值没有更改,因此没有更改
-event发生getimageurl()
处理程序,该处理程序将触发观察文件加载时。
要解决问题,请重置
&lt; input&gt;
的值,在复制所选文件的路径之后:demo 1
次要重构
renderimage()
实际上只是在使用观看
基本上创建一个fileReader
'sload
事件的异步回调。似乎可以通过将图像渲染代码直接移动到load
-event处理程序中来简化这可以简化这一点:The question assumes the
watch
callback isn't firing, but in this case, it's actually the<input>
that isn't firing its event.The
<input>
only fires thechange
/input
event when its value actually changes. When selecting the same file, the value hasn't changed, and thus nochange
-event occurs to call thegetImageUrl()
handler, which would've triggered thewatch
when the file gets loaded.To resolve the issue, reset the
<input>
's value after copying the selected file's path:demo 1
Minor refactoring
renderImage()
is actually just usingwatch
to essentially create an async callback forFileReader
'sload
event. It seems this could be simplified by moving the image rendering code into thatload
-event handler directly:Then you could remove
renderImage()
:...and also
state.image
:demo 2