繁体   English   中英

Vue.js 如何使用 v-model 和计算属性以及复选框镜像输入字段

[英]Vue.js How to mirror input field with v-model and computed property and a checkbox

我想弄清楚如何正确镜像两个输入字段并根据复选框值动态更改它们。 这是我能想到的将计算属性与 get 和 set 功能结合使用的最佳方法。 问题是当用户在运输详细信息中键入 (1)“ABC”,(2) 取消选中 (copy_chekcbox=false),(3) 在帐单详细信息中键入“123”,以及 (4) 重新检查 (copy_chekcbox=true) ( 5)帐单明细不会恢复为运输明细,这正是我所需要的。 带有步骤的图像

另外,是否有更短、更优的方法来镜像两个字段并根据复选框值更改它们的值?

先感谢您。

 <!DOCTYPE html> <html> <head> <title>My first Vue app</title> <script src="https://unpkg.com/vue"></script> </head> <body> <div id="app"> <p>Shipping details</p> <input v-model="shipping" type="text" /> <p>Same as shipping: <input type="checkbox" v-model="copy_chekcbox" /></p> <p>Billing details</p> <input v-model="billing" type="text" :disabled="copy_chekcbox" /> </div> <script> var app = new Vue({ el: '#app', data: { shipping_data: '', billing_data: '', copy_chekcbox: true, }, computed: { shipping: { get: function() { return this.shipping_data }, set: function(newValue) { if (!this.copy_chekcbox) { this.shipping_data = newValue } else { this.billing_data = newValue this.shipping_data = newValue } }, }, billing: { get: function() { return this.billing_data }, set: function(newValue) { if (!this.copy_chekcbox) { this.billing_data = newValue } else { this.billing_data = this.shipping_data } }, }, } }) </script> </body> </html>

在我看来,我认为最简单的方法是在 v-if 中使用两个输入:

<p>Shipping details</p>
<input v-model="shipping" type="text">

<p>Same as shipping: <input type="checkbox" v-model="copy_chekcbox"></p>

<p>Billing details</p>

<template v-if="copy_chekcbox">
  <input v-model="shipping" type="text">
<template>
<template v-else>
  <input v-model="billing" type="text">
</template>

这种方法的主要优点是您的 JavaScript 代码保持简单。

尝试这个:

billing: {
          get: function() {
            return this.copy_checkbox ? this.shipping_data : this.billing_data
          },

当您更改 copy_checkbox 并因此更新您的 billing_data 时,它应该为您的账单数据重新运行计算函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM