无法在 VueJS 组件中使用 jquery 插件

Cannot use jquery plugin inside VueJS component

我使用 VueJS 有一段时间了,它很棒。我已经能够将它与 jQueryUI(对于一个看起来很旧的网站)集成,并且我创建了一个日期选择器组件和一个日期时间选择器组件,两者都可以正常工作。

现在我正在尝试创建一个简单的 phone 数字组件,它只是提供一个带有有助于 phone 数字格式的掩码的输入。 jquery 的插件提供了屏蔽功能,它自己可以正常工作,但是如果我试图屏蔽组件内部的输入,它就不起作用。

这是 jsfiddle 中的示例代码:

Simple Masked Phone input component for vuejs 2.4.0 - jsfiddle

Javascript:

Vue.component('phone', {
  template: '#phone',
  props: {
    value : {
      type   : String,
      default: ''
    },
    mask: {
      type   : String,
      default: '(999) 999-9999'
    }
  },
  data: function() {
    return {
        internalValue: ''
    };
  },

    created: function() {
    this.internalValue = $.trim(this.value);
  },

  mounted: function() {
    $(this.$el).find('.phone:eq(0)').mask('(999) 999-9999');
  },

  methods: {
    updateValue: function (value) {
            this.$emit('input', value);
    }
  }
});

var vueapp = new Vue({
  el: '#content',
  data: {
    myphone: ''
  }
});

$('.phonex').mask('(999) 999-9999');

HTML:

<div id="content">
  <script type="text/x-template" id="phone">
    <input type="text" class="phone" v-model="internalValue" v-on:input="updateValue($event.target.value)" />
  </script>

  <label>Vue Phone</label>
  <phone v-model="myphone"></phone>
  <br />
  {{ myphone }}
  <br />

  <label>Simple Phone</label>
  <input type="text" class="phonex" />
</div>

这是我看到的:

依赖关系:

我这里有什么地方做错了吗?谢谢。

您不需要 jquery 中的 .find('.phone:eq(0)'),删除它似乎可以修复屏蔽(如图 here 所示),尽管这似乎会扰乱 Vue 的数据捆绑。

进一步挖掘后,它看起来像是 known issue

地址为here:

Vue is a jealous library in the sense that you must let it completely own the patch of DOM that you give it (defined by what you pass to el). If jQuery makes a change to an element that Vue is managing, say, adds a class to something, Vue won’t be aware of the change and is going to go right ahead and overwrite it in the next update cycle.

解决此问题的方法是在元素上调用 .mask 时添加事件处理程序。

例如:

mounted: function() {
  var self = this;
    $(this.$el).mask('(999) 999-9999').on('keydown change',function(){
        self.$emit('input', $(this).val());
    })
  },

这是 fiddle 的修复:https://jsfiddle.net/vo9orLx2/