javascript - vuejs - 在同一个文件中同步变量
问题描述
我有一个 vue(版本 2.x)文件,其中有 3 个字段 -input1 x input2 = result
现在,当我更改其中任何一个时,其他两个应该即时更新。我尝试使用watch
属性,但这会导致无限循环,因为观察者不断互相调用。
我在这里缺少任何与 vue 相关的助手吗?任何帮助,将不胜感激。
请参阅此示例代码。
<template>
<input v-model="input1"></input>
<input v-model="input2"></input>
<input v-model="conversionRate"></input>
</template>
<script>
export default {
data() {
input1: null,
input2: null,
conversionRate: null
},
watch: {
input1() {
this.input2 = this.input1 * this.conversionRate
},
input2() {
this.input1 = this.input2 * this.conversionRate
},
conversionRate() {
this.input2 = this.input1 * this.conversionRate
}
}
}
</script>
解决方案
由于所有三个模型都相互依赖,因此会导致无限循环。
根据您的要求,您可以使用计算的 setter。
HTML
<div id="app">
<input type="number" placeholder="amount" v-model="inputA"> X
<input type="number" placeholder="rate" v-model="conversionRate"> =
<input type="number" placeholder="total" v-model="total">
</div>
脚本
new Vue({
el: "#app",
data: {
total: 0,
conversionRate: 1
},
computed: {
inputA: {
get() {
return this.total / this.conversionRate;
},
set(newVal) {
this.total = newVal * this.conversionRate;
}
}
}
});
这是工作小提琴
推荐阅读
- amazon-web-services - ecs.amazonaws.com 和 ecs-tasks.amazonaws.com 有什么区别?
- sapui5 - 如何在没有数据绑定的情况下使用 sapui5 SmartField?
- javascript - 两个javascript参数如何传递“this”
- arrays - mongodb 匹配数组中的项目作为聚合管道的一部分
- javascript - Weglot 链接挂钩不起作用(在粘性标题上)
- vue.js - Vue 数据、计算和方法
- c - 将指向多维数组的指针作为参数传递
- symfony - Symfony 4. 如何将 DateType 扩展为 HiddenType
- android - 哪个更有效依赖组件或子组件以及何时使用什么
- java - 获取所有唯一的文件名