【问题标题】:this.$root.$emit run the event twicethis.$root.$emit 运行该事件两次
【发布时间】:2018-10-04 21:20:10
【问题描述】:

我开始使用vue.js,对于我的项目,我看到需要使用来自 vue.js 官方网站的以下 select2 包装器组件,这是链接:https://vuejs.org/v2/examples/select2.html 问题在于我现在需要发出一个根事件来更改 select2 的值,这就是它在以下部分添加一行代码的原因:

.on('change', function () {
  vm.$emit('input', this.value);
  vm.$root.$emit('eventing', this.value);
})

这行得通,但是我从vue的控制台意识到,我的事件被广播了2次,我认为是我的代码问题并删除了添加的行,但是输入事件也发出了两次,我的问题:是这种正常行为?这样做是不好的做法吗?我缺少一些东西。对我来说,这是一个问题,因为我的事件发生了两次,所以我进行了 ajax 调用并且它被执行了两次。

【问题讨论】:

标签: javascript vuejs2 jquery-select2


【解决方案1】:

有一种更简单的方法可以用vue将数据绑定到select2:

Vue.directive('select', {
  twoWay: true,
  bind: function (el, binding, vnode) {
      $(el).select2().on("select2:select", (e) => {
        // v-model looks for
        //  - an event named "change"
        //  - a value with property path "$event.target.value"
        el.dispatchEvent(new Event('change', { target: e.target }));
    });
  },
 });

这将绑定到 Vue 实例上的所有选择,以便它们与 v-model 一起使用,您可以使用 select2

之后,将 v-model="" 和 v-select="" 添加到您的 select2 目标中,然后您就设置好了。

归功于:Select2 on change event is not working in Vuejs

【讨论】:

    【解决方案2】:

    尝试在 beforeDestroy 中关闭...

    beforeDestroy() {
      this.$root.$off('change', yourFunction)
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多