【发布时间】: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