javascript - 如果与 v-for 一起使用,则无法设置默认输入单选

标签 javascript jquery html vue.js vuejs2

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

我已经尝试过这个:-

:checked="index == 1"

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

:checked="{ index == 1 }"

但他们都不适合我。

下面是我的模板片段:-

<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(){

    }
});

}

任何帮助将不胜感激。

最佳答案

您无需设置 checked吸引你自己。通过使用v-model="selectedShape"您已将所有 radio 输入链接到 selectedShape .

您已经可以通过控制selectedShape的值来控制检查的属性。 .

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

<input type="radio" :id="shape" :value="shape" v-model="selectedShape"> (删除:checked="index == 1")

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

关于javascript - 如果与 v-for 一起使用,则无法设置默认输入单选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487859/

相关文章:

javascript - 编辑图表后更新 HighChart 上的系列数组

javascript - 推特 Bootstrap 。折叠子元素

javascript - 将 DIV 和 SVG 图层展平为单个图像

javascript - @ 符号在 javascript 导入中起什么作用?

javascript - 仔细看看 HTML5 Canvas fillStyle

javascript - jQuery 文本到链接脚本?

javascript - 等待元素显示给用户

javascript - 每个 div 获取父级的高度 - jQuery 方法

JavaScript onClick 添加类

javascript - 组织外部 Javascript 文件