【问题标题】:Unable to set default input radio checked if used with v-for如果与 v-for 一起使用,则无法设置默认输入单选
【发布时间】:2018-03-26 09:15:11
【问题描述】:

我正在尝试将单选按钮添加到我的代码中。除了一件事,一切都很好。当我使用 v-for 循环创建收音机时,未检查默认收音机。如果我把它放在 for 循环之外,它就可以工作。

我已经试过了:-

:checked="index == 1"

还有这个(如一些答案中所建议的):-

:checked="{ index == 1 }"

但它们都不适合我。

下面是我的模板 sn-p:-

<div class="props-data">
  <!-- <input type="radio" :checked="currentStep==1"> -->
  <span v-for="(shape, index) in availableShapes" v-if="currentStep==1">
    <div>
      <input type="radio" :id="shape" :value="shape" v-model="selectedShape" :checked="index == 1">
      <label :for="shape">{{shape}}</label>
    </div>
  </span>
</div>

注意:- steps-container 是创建 Vue 实例的主要父类。

下面是我的js代码:-

window.onload = function(){
new Vue({
    el: '#steps-container',
    data: function() {
        return {
            currentStep: 1,
            availableShapes: ['Rectangle','Circle','Square','Ellipse'],
            selectedShape: undefined
        };
    },
    methods: {
        cancel: function(){
            this.currentStep = 1;
            jQuery('#main-action').text('Go to step '+ (this.currentStep+1));
        },
        nextStep: function(){
            if( this.currentStep == 2 ){
                jQuery('#main-action').text('Startover');
                this.currentStep++;
            }
            else{
                if( this.currentStep == 3 ){
                    this.currentStep = 1;
                }
                else{
                    this.currentStep++;
                }
                jQuery('#main-action').text('Go to step '+ (this.currentStep+1));
            }
        }
    },
    mounted: function(){
    },
    updated: function(){

    }
});

}

任何帮助将不胜感激。

【问题讨论】:

  • @uzaif 不,它不适合我

标签: javascript jquery html vue.js vuejs2


【解决方案1】:

您不需要自己设置checked attr。通过使用v-model="selectedShape",您已将所有无线电输入与selectedShape 链接起来。

你已经可以通过控制selectedShape的值来控制checked attr了。

所以将selectedShape的初始值设置为默认值,默认会勾选。

&lt;input type="radio" :id="shape" :value="shape" v-model="selectedShape"&gt;(删除:checked="index == 1"

    data: function() {
        return {
            //...
            selectedShape: "THE DEFAULT VALUE"
        };
    },

【讨论】:

  • 好吧.. Vue 本身就是一个魅力
  • 没错……但有时我会卡在文档中……哈哈
猜你喜欢
  • 1970-01-01
  • 2014-10-27
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
相关资源
最近更新 更多