javascript - 使用 VueJS 2 在 Bootstrap 开关上触发事件

标签 javascript jquery twitter-bootstrap vue.js

我处理的是boostrap switch

在 JQuery 中,这很简单,您可以按照文档状态进行操作:

  $('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
    console.log(this); // DOM element
    console.log(event); // jQuery event
    console.log(state); // true | false
});

但是在 VueJS 中,我无法将元素绑定(bind)到值:

<div id="vue-instance">
  <input type="checkbox" name="my-checkbox" checked @click="log">
</div>

var vm = new Vue({
  el: '#vue-instance',
  data: {

  },
  methods:{
      log(){
          alert('ok');
      }
  },
  mounted(){
    $("[name='my-checkbox']").bootstrapSwitch();

  }
});

这是 fiddle :https://jsfiddle.net/xoco70/tfkLkLqw/1/

最佳答案

如果您确实需要使用此功能,只需绑定(bind)到 mounted 生命周期 Hook 上的更改即可。

var vm = new Vue({
  el: '#vue-instance',
  data: {

  },
  methods:{
      log(event, state){
          alert('ok');
      }
  },
  mounted(){
    $("[name='my-checkbox']").bootstrapSwitch();
    $('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', this.log.bind(this));
  }
});

我说如果您确实需要使用它,因为您将 Vue.js 的数据驱动方法与使用 JQuery 查询 View 混合在一起>。我还尝试提出一个解决方案,您可以使用 Vue 绑定(bind),以便您可以对模型中的事件或更改使用react,但当切换已切换。

工作示例

var vm = new Vue({
  el: '#vue-instance',
  data: {
    bSwitch: null
  },
  methods:{
      log(event, state){
          this.bSwitch = state;
          console.log('switch to state ' + state );
      }
  },
  mounted(){
  	$("[name='my-checkbox']").bootstrapSwitch();
    $('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', this.log.bind(this));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/bootstrap-switch@3.3.4/dist/js/bootstrap-switch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-switch@3.3.4/dist/css/bootstrap3/bootstrap-switch.css" rel="stylesheet"/>

<div id="vue-instance">
  Switch State: {{bSwitch}}
  <br>
  <input type="checkbox" name="my-checkbox">
</div>

关于javascript - 使用 VueJS 2 在 Bootstrap 开关上触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598404/

相关文章:

javascript - 带有顶级数组的 Handlebars.js 模板

javascript - 单击按钮更改事件的 Bootstrap 选项卡

javascript - 如果未经过身份验证,则重定向并在 Promise 中设置 State

javascript - firepad:作为 firepad 的 codemirror div 中的默认文本的变量

JavaScript:滑动 Action 模式实现

javascript - 如何在 jQuery 中创建无限循环?

javascript - Dnd-kit:在 Droppable 上拖动时事件项目会失去顺序

javascript - Moment js 给出的星期不正确

css - 未使用 Twitter Bootstrap 修复时居中导航栏内容?

html - 如何使 Twitter Bootstrap 网格列全长窗口,即使里面的内容很少