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

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

我想弄清楚如何正确镜像两个输入字段并根据复选框值动态更改它们。这是我能想到的使用具有获取和设置功能的计算 属性 的最佳方法。 问题是当用户在送货详细信息中键入 (1)“ABC”,(2)取消选中 (copy_chekcbox=false),(3)在帐单详细信息中键入“123”,以及 (4)返回检查 (copy_chekcbox=true) (5)帐单明细不会恢复为运输明细,这是我需要的。 Image with steps

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

提前致谢。

<!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>

试试这个:

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

当您更改 copy_checkbox 并因此更新您的 billing_data.

时,它应该为您的结算数据重新运行计算函数

在我看来,我认为最简单的方法是对 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 代码保持简单。