如何用一个单选按钮更新2个属性

how to update 2 attributes with one radio button?

本文关键字:2个 属性 更新 单选按钮 何用一      更新时间:2023-09-26

我不确定我是否只是停留在jQuery的心态中,但有没有办法用一个单选按钮更新两个模型属性?目前我有两个隐藏的单选按钮。可见的一个使用@click事件检查第二个,该事件获取下一个输入并将其设置为true。

var app = new Vue({
  data: {
    order: { 
      amount: 
      type:
    }
  },
  methods: {
    selectType: function(e) {
      e.currentTarget.getElementSibling.checked = true;
    }
  }
}); 
<form>
  <input type="radio" v-model="order.amount" value=15 @click="selectType">$15</input><br>
  <input type="radio" v-model="order.type" value="small" style="display:none">
  <input type="radio" v-model="order.amount" value=15 @click="selectType">$15</input><br>
  <input type="radio" v-model="order.type" value="med" style="display:none" @click="selectType">
  <input type="radio" v-model="order.amount" value=20 >$20</input><br>
  <input type="radio" v-model="order.type" value="large" style="display:none">
</form>

根据我的理解,v-model语法最适合绑定单个值。您可以尝试以某种方式将值设置为JSON字符串,然后对其进行解码……但这听起来是个坏主意。这里有三个想法:

使用JQuery和Vue

相反,您可以为每个想要的值赋予单选按钮属性,然后在单击回调中解析出这些属性。例如:

<input type="radio" name="rad" btn-amount="10" btn-type="small" @click="selectType($event)">$15 <br>
<input type="radio" name="rad" btn-amount="15" btn-type="med" @click="selectType">$15<br>
<input type="radio" name="rad" btn-amount="20" btn-type="large" @click="selectType">$20<br>

然后是一种方法:

selectType: function(e) {
  this.order.amount = $(e.currentTarget).attr('btn-amount');
  this.order.type = $(e.currentTarget).attr('btn-type');
}

这是一个JSFiddle展示它的行动。

仅使用Vue

或者,您可以将选项的数据移动到vue实例中,而不是将它们放在单选按钮上。例如,将options数组添加到数据中,并在HTML中对其进行迭代以创建按钮

<div v-for="option in options">
  <input type="radio" name="rad" @click="selectType(option)">${{ option.amount }}
</div>

请注意,您可以将for循环中的当前option传递给单击处理程序!这意味着您可以将selectType写成:

selectType: function(option) {
  this.order = option;
}

这是非常干净的,如果你打算保持单选按钮的功能简单,我建议你这样做。

这里有一个JSFiddle展示了它的实际操作。

使用Vue组件

但是,如果你打算让事情变得更复杂,你可能需要将单选按钮功能封装到一个组件中。

考虑模板:

<template id="radio-order">
  <div>
    <input type="radio" :name="group" @click="setOrder">${{ amount }}
  </div>
</template>

及其相关组件:

Vue.component('radio-order', {
  template: '#radio-order',
  props: ['group', 'amount', 'type'],
  methods: {
    'setOrder': function() {
      this.$dispatch('set-order', {
        amount: this.amount,
        type: this.type
      })
    }
  }
});

现在,您可以制作<radio-order>组件,在单击时分派set-order事件。父实例可以侦听这些事件并采取适当的操作。

诚然,这种方法比较冗长。但是,如果您正在考虑实现更复杂的功能,这可能是一条可行的道路。

这是一个JSFiddle的行动。

当然,还有很多方法可以解决这个问题,但我希望这些想法能有所帮助!