【发布时间】:2025-12-26 00:40:10
【问题描述】:
我在 laravel 中创建了一个包装好的 vue 组件来包装 jQuery select2 元素。 基于in this code。
当 select.options 中的值发生变化时,选择元素会被复制。就像下图一样。
该选择仅在第二次选择中有效。
不知道是什么问题,我在自己做的代码下面加上options变量的内容。
select2.vue
<template>
<div>
<select>
<slot></slot>
</select>
</div>
</template>
<script>
export default {
name: "select2",
props: ['options', 'value'],
mounted: function () {
let vm = this
$(this.$el)
// init select2
.select2({ data: this.options })
.val(this.value)
.trigger('change')
// emit event on change.
.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 })
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
}
</script>
<style scoped>
</style>
blade文件调用
<select2 :options="select.options" v-model="select.value"></select2>
select.options数据
[
{
"text": "Group 1",
"children": [
{
"id": 1,
"text": "Element 1"
},
{
"id": 2,
"text": "Element 2"
}
]
},
{
"text": "Group 2",
"children": [
{
"id": 3,
"text": "Element 3"
},
{
"id": 4,
"text": "Element 4"
}
]
}
]
【问题讨论】:
标签: laravel vue.js vue-component