无法将已检查的单选值重置为默认值(Vue js)

时间:2019-02-21 16:46:27

标签: vue.js

默认情况下,我使用本地取件选项,其值为1。当用户更改为免费送货时,将出现一些情况:如果邮政编码有效,则它将更改为免费送货,否则,将显示警报消息。显示,并且将再次检查本地取件。问题是,如果邮政编码不合适,我可以将默认传递值设置为1。但是收音机显示选中的选项为2。

<label v-for="(del, index) in delivery" :key="index">
    <input type="radio" name="del" :value="del.value" v-model="defaultDelivery" @change="changeDelivery(del.value)">{{ del.label }}
</label>


export default {
    data () {
        return {
            delivery: [
                {value: 1, label: 'Local pickup'},
                {value: 2, label: 'Free Delivery'}
            ],
            accepted_zips: [
              12345,
              12346
            ],
            defaultDelivery: 1,
            zip_code: 78745
        }
    },
    changeDelivery: function(val) {
        if(val == 2 && !this.accepted_zips.includes(this.zip_code))
        {
            this.defaultDelivery = 1 //it should set 1 as checked again! But it is not aplied
            alert('Sorry but currently we don't cover your area.')
        }
    },

1 个答案:

答案 0 :(得分:0)

请注意,“不要”中的撇号将关闭字符串,并且您没有将方法放在methods节中。对此进行更正,您的代码对我来说很好。

new Vue({
  el: '#app',
  data() {
    return {
      delivery: [{
          value: 1,
          label: 'Local pickup'
        },
        {
          value: 2,
          label: 'Free Delivery'
        }
      ],
      accepted_zips: [
        12345,
        12346
      ],
      defaultDelivery: 1,
      zip_code: 78745
    };
  },
  methods: {
    changeDelivery(val) {
      if (val == 2 && !this.accepted_zips.includes(+this.zip_code)) {
        this.defaultDelivery = 1 //it should set 1 as checked again! But it is not aplied
        alert('Sorry but currently we don\'t cover your area.')
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>ZIP code <input v-model="zip_code"></div>
  <label v-for="(del, index) in delivery" :key="index">
    <input type="radio" name="del" :value="del.value" v-model="defaultDelivery" @change="changeDelivery(del.value)">{{ del.label }}
</label>
</div>