【问题标题】:Select2 in Vue.js is not definedVue.js 中的 Select2 未定义
【发布时间】:2019-06-26 00:18:12
【问题描述】:

我想在 Vue.js 中使用 Select2 来显示一些可选择的选项,但是我实现它时,总是出现错误:

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)

我使用以下命令安装了 npm 包:npm install --save select2。不知道这个是不是官方包。我在 index.html 中包含了 cdn 链接,并在一个特殊文件 (jquery.js) 中添加了一个要求,该文件直接包含在 main.js 中

jquery.js:

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

选择2.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>

【问题讨论】:

  • 真的不推荐jquery和vue一起使用。如果您需要丰富的下拉菜单,您可以使用例如vuetify select
  • 我知道,但我的老板坚持 Select2 ...

标签: vue.js vuejs2 jquery-select2


【解决方案1】:

我也推荐其他amazing Vue component Select2

但是如果你不能让你的老板相信你可以很容易地在 vue 系统中更新模型并且你不得不花费大量时间来开发,这里有一些想法可以尝试:

删除jquery.js,修改Select2.vue,在select2.vue中添加require('select2')

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

然后,在您的父组件中使用带相对路径的导入:

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

我想你从Wrapper Component Example from Vue docs 复制所有内容,一切都应该正常......

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 2016-01-21
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2019-02-23
    • 2019-10-09
    相关资源
    最近更新 更多