【问题标题】:How to get toggle switch state in vue app如何在 vue 应用中获取切换开关状态
【发布时间】:2020-07-02 14:43:33
【问题描述】:

我正在测试 Bootstrap 5 alpha。他们从依赖项中删除了 jQuery,如果该框架用于基于 Vue 的应用程序的 UI,这是一个改进。在 Bootstrap 4.5 中,我注意到如果所有 B/S 4 依赖项都正确包含在应用程序的 main.js 文件中,则切换开关不起作用。

由于使用了 Vanilla JavaScript,在 v5 中一切正常。我想问一下在我的 Vue 应用程序中单击时如何获取切换开关的状态。我想使用这个 Bootstrap 组件创建一些设置,但我不确定如何使用 v-on:click.prevent 事件绑定来管理开/关状态。欢迎提出任何建议。

【问题讨论】:

  • 您也可以使用Bootstrap-Vue,它有一个switch checkbox。虽然它目前使用的是 Bootstrap 4,而不是 Bootstrap 5,但它正在计划中。

标签: javascript twitter-bootstrap vue.js


【解决方案1】:

您可以使用v-model 指令来创建双向数据绑定。

<div class='form-check form-switch'>
  <input class='form-check-input' type='checkbox' id='flexSwitchCheckDefault' v-model='switch'>
  <label class='form-check-label' for='flexSwitchCheckDefault'>Default switch checkbox input</label>
</div>

Example

或者作为组件使用,例如switch-component

<switch-component
  id='switch'
  v-model='switch'>
  Default switch
</switch-component>
Vue.component('switch-component', {
  props: ['id', 'value'],
  inheritAttrs: false,
  template: `
    <div class='form-check form-switch'>
      <input
        class='form-check-input'
        type='checkbox'
        v-bind='$attrs'
        :checked='value'
        @change='$emit("input", $event.target.checked)'>
      <label
        class='form-check-label'
        :for='id'>
        <slot/>
      </label>
    </div>
  `
})

Example

【讨论】:

  • 所以v-model 会自动检测开关是否切换,正如我从示例中看到的那样,对吧?
  • 是的。请阅读vuejs.org/v2/guide/forms.html,有一个复选框部分。
  • 知道,但从未在带有 vue 的表单中使用过切换开关或复选框。感谢您的帮助
猜你喜欢
  • 2018-10-11
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
相关资源
最近更新 更多