【问题标题】:VueJS How to trigger a method by selecting different radio buttons?VueJS 如何通过选择不同的单选按钮来触发方法?
【发布时间】:2021-03-21 16:33:45
【问题描述】:

我有一个简单的 VueJS 表单,在表单的开头有一个单选按钮组,其中包含三个不同的选项。表单的其余部分将根据此单选选项显示或隐藏。当我使用 @click 时,它并没有做我想要的确切事情。这是我的单选按钮;

                <div>
                <label class="form-radio">
                  <input type="radio" name="internetconnectiontype" id="dynmaicIP" value="dynamicIP">
                  <span><label>Dynamic IP</label></span>
                </label>

                <label class="form-radio">
                  <input type="radio" name="internetconnectiontype" id="staticIP" value="staticIP">
                  <span><label>Static IP</label></span>
                </label>

                <label class="form-radio">
                  <input type="radio" name="internetconnectiontype" id="pppoe" value="pppoe" checked>
                  <span><label>PPPoE</label></span>
                </label>
            </div>

在这些按钮之后,我有两个不同的组,换句话说就是两个不同的 div 来显示和隐藏。首先,如果选择Dynamic IP,会隐藏两个div,如果选择Static IP,那么只有第一个div可见,如果选择PPPoE,只会出现第二个div。

当我使用v-model 时,它会在我在收音机之间切换时给我值,之后我编写了一个方法,比如如果选择了这个值然后到那个,如果这个值被选择到那些等等......但它没有也不起作用,我创建了变量并将它们默认设置为 false 并尝试在 true 和 false @change 之间切换它们,但我无法管理。我该怎么做?

【问题讨论】:

  • 请提供您的功能以便我们提供帮助

标签: vue.js radio-button show-hide v-model


【解决方案1】:

var app = new Vue({
  el: '#app',
  data() {
    return {
      connType: "",
    };
  },
})
body{
margin: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
      <label class="form-radio">
        <input
          type="radio"
          name="internetconnectiontype"
          id="dynmaicIP"
          value="dynamicIP"
          v-model="connType"
        />
        <span><label>Dynamic IP</label></span>
      </label>

      <label class="form-radio">
        <input
          type="radio"
          name="internetconnectiontype"
          id="staticIP"
          value="staticIP"
          v-model="connType"
        />
        <span><label>Static IP</label></span>
      </label>

      <label class="form-radio">
        <input
          type="radio"
          name="internetconnectiontype"
          id="pppoe"
          value="pppoe"
          v-model="connType"
        />
        <span><label>PPPoE</label></span>
      </label>
    </div>
    <div v-if="connType === 'dynamicIP'">
      {{ connType }}
    </div>
    <div v-else-if="connType === 'staticIP'">
      {{ connType }}
    </div>
    <div v-else-if="connType === 'pppoe'">
      {{ connType }}
    </div>
    <div v-else>Please select</div>
  </div>
</div>

【讨论】:

  • 谢谢,我试过了,它确实有效。但我还有一个问题。我想为我的拨动开关做一个类似的逻辑。如果单击 toggle1,我希望取消选中我的 toggle2。假设先打开toggle1,然后单击toggle2。此时我只想选择toggle2,而不是另一个。我该怎么做?
  • 使用单选按钮,您一次只能选择一个。选择一个会自动取消选择其他。不确定您要做什么。
猜你喜欢
  • 2013-07-30
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 2012-10-16
  • 2016-02-12
  • 1970-01-01
  • 2021-01-26
  • 2016-05-03
相关资源
最近更新 更多