Peter
Peter

Reputation: 35

Select2 in Vue.js is not defined

I want to use Select2 with Vue.js to display some selectable options, but however I implement it, there is always the error:

Uncaught ReferenceError: select2 is not defined

at Object.select2 (external "select2":1)
at __webpack_require__ (bootstrap:766)
at fn (bootstrap:129)
at Module../src/jquery.js (jquery.js:3)
at __webpack_require__ (bootstrap:766)
at fn (bootstrap:129)
at Module../src/main.js (main.js:1)
at __webpack_require__ (bootstrap:766)
at fn (bootstrap:129)
at Object.0 (Home.vue?1405:1)

I installed the npm package with this command: npm install --save select2. I don’t know if this is the official package. I included the cdn link in the index.html and I added a require in a special file (jquery.js) which is directly included in main.js

jquery.js:

import jQuery from 'jquery'
window.jQuery = window.$ = jQuery
require('select2')

Select2.vue:

<script>
    import jQuery from 'jquery';
    let $ = jQuery;

    export default {
        name: 'select2',
        props: ['options', 'value'],

        mounted: function () {

            var vm = this

            $(this.$el).select2({
                    data: this.options,
                    tags: true
                }).on('change', function () {
                    vm.$emit('input', this.value)
                });
        },
        watch: {
            value: function (value) {
                // update value
                $(this.$el)
                    .val(value)
                    .trigger('change')
            },
            options: function (options) {
                // update options
                $(this.$el).empty().select2({data: options,tags: true})
            }
        },
        destroyed: function () {
           $(this.$el).off().select2('destroy')
        }
    }
</script>

Upvotes: 0

Views: 4944

Answers (1)

Juanmabs22
Juanmabs22

Reputation: 1300

I also recommend other amazing Vue component Select2.

But if you cannot convince your boss that you will get the model updated in the vue system easy and you hace to spend a lot of time to develop, here are some ideas to try:

Delete jquery.js, and change Select2.vue to add require('select2') to select2.vue:

<script>
  import jQuery from 'jquery';
  window.jQuery = window.$ = jQuery;
  require('select2');
 ...

then, in your parent component use import with relative paths:

import Select2 from "../stangeComponents/Select2.vue";

I suppose you copy all from the Wrapper Component Example from Vue docs and everything should work...

Hope it helps :)

Upvotes: 3

Related Questions