javascript - 当另一个字段发生变化时更新一个字段 - Vue
问题描述
我试图从本质上创建一个双向计算器,并且我选择使用英寸到毫米作为示例。
在此处查看沙箱:https ://q8y4s.csb.app/
<template>
<div>
<input type="number" v-model="inches" placeholder="Inches" />
<br />
<input type="number" v-model="mm" placeholder="Millimeters" />
</div>
</template>
<script>
export default {
data() {
return {
inches: "",
mm: "",
};
},
watch: {
inches: function (newVal) {
this.mm = newVal * 25.4;
},
mm: function (newVal) {
this.inches = newVal / 25.4;
},
},
};
</script>
问题从毫米到英寸。我不完全确定发生了什么,但它似乎是某种反馈循环。我知道我可以使用计算来实现这个特定的功能,但我更喜欢使用观察者,因为我的项目中的“观察”字段有更多的逻辑。
本教程使用米到公里并完成同样的事情,但我不确定为什么毫米到英寸会产生“反馈循环”效应
解决方案
您可以做的是创建一个安全阀来防止递归。就像是:
export default {
data() {
return {
isChangingMm: false,
isChangingInches: false,
// others
}
},
watch: {
inches: function (newVal) {
if (!this.isChangingMm) {
this.isChangingInches = true
this.mm = newVal * 25.4
this.isChangingInches = false
}
},
mm: function (newVal) {
if (!this.isChangingInches) {
this.isChangingMm = true
this.inches = newVal / 25.4
this.isChangingMm = false
}
}
},
}
推荐阅读
- java - 将 CSV 直接加载到对象集合中
通过 Java 流 API - android - 升级到 android studio 4.0 后未解决的数据绑定参考
- discord.js - 我如何将角色与用户进行比较或查看给定的所需角色是否是他们的最高角色?
- arrays - 在 React 中,如何在列表中找到符合某些条件的第一项?
- c# - EF Core:发送到数据库的重复值
- c# - 如何从 JSON 中读取列表
- php - 使用 Symfony Messenger 异步发送电子邮件时如何翻译?
- postman - 我的邮递员 REST API 的邮递员似乎无法工作
- javascript - 在 Javascript 中使用外部文件
- gcc - 将 xgboost 安装到 AWS EC2 Linux 实例