How to resolve that conflict between vue and traditional jquery plug in

  • 2021-08-05 08:27:35
  • OfStack

This article mainly introduces how to solve the vue and traditional jquery plug-in conflict, this site feels quite good, now share with you, also give you a reference. Follow this site from 1 to have a look

For example, select2 plug-in based on jquery has many problems when used alone under vue. In fact, for this kind of plug-in, it can be wrapped with custom instructions and components of vue to solve conflicts. Citing two examples of official vue 1.0 and 2.0, learn 1.

Example 1.0 Example 2.0

Be crowned with success. Talk about vueN1-based, for drop-down single choice, use the official example of vue. For multi-choice, look at what you wrote below. The core is to use el and vm of instruction objects to obtain the corresponding objects of select drop-down list changed by select2. The key point is to use jquery to wrap native elements and then use. val () to obtain multi-choice values.


<body>
  <div id="el">
   <p>Selected: {{selected}}</p>
   <select v-select3="selected" multiple class="app1" >
    <option value="0">default</option>
    <option v-for="o in options" :value="o.id">{{ o.text }}</option>
   </select>
    
    <p>Selected: {{market}}</p>
   <select v-select3="market" multiple class="app2" >
    <option value="0">default</option>
    <option v-for="o in markets" :value="o.id">{{ o.text }}</option>
   </select>
  </div>
  <script>
    Vue.directive('select3', {
     twoWay: true,
     priority: 1000,

     params: ['options'],
      
     bind: function () {
      var self = this;
      $(this.el)
       .select2()
       .on('change', function () {
        self.set($(self.el).val());
        console.log($(self.el).val());
        if ( self.expression == 'selected') {
          self.vm.market = [];
        }

       })
     },
     update: function (value) {
      
      $(this.el).val(value).trigger('change')
     },
     unbind: function () {
      $(this.el).off().select2('destroy')
     }
    })

    var vm = new Vue({
     el: '#el',
     data: {
      selected: 0,
      market: '',
      options: [
       { id: 1, text: 'hello' },
       { id: 2, text: 'what' }
      ],
      markets: [
        { id: 1, text: ' Wenshan 2 Handcart ' },
        { id: 2, text: ' Little brother 2 Handcart ' }
      ]
     }
    });
    setTimeout(function () {
     vm.market = 0;
    }, 0);
  </script>
</body>

In addition, when inserting the default value, pay attention to making an asynchronous insert, because the vue update page is asynchronous, and here I made an setTimeout (, 0).

In addition, in a single page, consider setting 1 status bit vm. isInit when show of SSpa, which means that if the default option is initialized, the emptying and obtaining of 1 values will not be reset when judging whether relevant changes are triggered in onchange.


Related articles: