【问题标题】:Vue.js How to mirror input field with v-model and computed property and a checkboxVue.js 如何使用 v-model 和计算属性以及复选框来镜像输入字段
【发布时间】:2021-12-26 12:23:54
【问题描述】:

我试图弄清楚如何正确镜像两个输入字段并根据复选框值动态更改它们。这是我能想到的将计算属性与 get 和 set 功能结合使用的最好方法。 问题是当用户在运输详细信息中键入 (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>

【问题讨论】:

  • 只是提到你在 copy_checkbox 中有错字:)

标签: javascript html vue.js nuxt.js


【解决方案1】:

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

【讨论】:

  • 谢谢!这是一种非常简单而优雅的方法,可以解决我的问题。
【解决方案2】:

试试这个:

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

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

【讨论】:

  • 嗯,问题是值只在浏览器中发生变化,而在 vue.js 数据属性中没有变化:i.imgur.com/yGjgKX1.png
  • 如果您想在数据中更改它,您应该在copy_checkbox 上使用watch,如果更改为true,则将billin_data 设置为shipping_data。还要添加第二个watchshipping_data,如果设置了copy_checkbox,也会更新你的billing_data。在这种情况下,您可以完全删除您的 2 个计算属性。
  • 好的,谢谢你的解释。
猜你喜欢
  • 2018-01-09
  • 1970-01-01
  • 2019-03-25
  • 2020-04-17
  • 2021-12-21
  • 1970-01-01
  • 2021-03-05
  • 2016-09-17
  • 2019-08-26
相关资源
最近更新 更多