【发布时间】:2020-08-18 12:08:08
【问题描述】:
我有一个使用 JS 的 Vue 应用程序。我需要使用一些 Select2 来动态加载值,等等。我为我的 Select2 制作了一个 Vue 组件,除了一个问题外,它工作得非常好。我正在使用 Ajax 来获取 Select2 的动态选项,但是当我的 Select2 安装时,它不会加载 Ajax URL 的值。这是我的代码:
<template>
<table class="table">
<thead>
<tr>
<th>Substance</th>
<th>Tested</th>
<th>Results</th>
<th>Cause of Death</th>
<th>Person Perscribed For</th>
<th>Category</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="index in SubstanceRows" :key="index">
<td><input type="text" class="form-control form-control-sm substance-row" /></td>
<td><select2 class="js-example-basic-single tested-row" :apiurl="SummaryTested" style="width: 100%;"></select2></td>
<td><select2 class="js-example-basic-single result-row" :apiurl="SummaryResult" style="width: 100%;"></select2></td>
<td><div class="form-check"><input type="checkbox" class="form-check-input cause-of-death-row" value=""></div></td>
<td><select2 class="js-example-basic-single obtained-for-row" :apiurl="DrugObtainedFor" style="width: 100%;"></select2></td>
<td><div class="form-check"><input type="text" class="form-control form-control-sm category-row" /></div></td>
</tr>
</tbody>
</table>
</template>
<script type="text/x-template" id="select2-template">
<select>
<slot></slot>
</select>
</script>
这是我的组件:
Vue.component('select2', {
props: ['apiurl', 'id'],
template: '#select2-template',
mounted: function(){
this.loadSelect2
},
watch: {
loadSelect2: function() {
var vm = this
var apiURL = this.apiurl
$(this.$el).select2({
placeholder: "Select an option",
allowClear: true,
templateResult: dropdownTemplate,
templateSelection: dropSelection,
ajax: {
url: function(params){
url = 'api/variable/' + apiURL
if(params.term) url = 'api/variable/' + apiURL + '/' + params.term
return url
}
}
})
//Check if it has a value assigned
if (vm.$root[apiURL] && vm.$root[apiURL] != ''){
$.ajax({
type: 'GET',
url: '/api/variable/' + apiURL + '/' + vm.$data[apiURL]
}).then(function(data) {
var option = new Option(data.results[0].label, data.results[0].id, true, true)
element.append(option).trigger('change')
element.trigger({
type: 'select2:select',
params: {
data: data.results
},
templateResult: dropdownTemplate,
templateSelection: dropSelection
})
})
}
}
}
})
我卡住的部分是,如您所见(或未见),我使用 v-for 生成这些字段,使用我在 Vue 应用程序中声明的变量。我有一个按钮,可以根据需要添加更多这些(目前我只是将 +1 添加到变量中)。我遇到的问题是在为 select2 做 ajax 时。 /api/variable + apiURL的部分,第一次生成时,变量apiURL是未定义的。我应该提到 v-for 变量 SubstanceRows 的初始值为 3(因此加载时我有三行)。但是,当我使用按钮添加一行时,它工作得很好,并且 url 按预期加载。我猜这是异步的一些问题,但我真的没有足够的 Vue 经验来弄清楚它是什么。
另外,脚本部分id=select2-template,我按照指南进行操作,但我不知道它的作用。
【问题讨论】:
标签: vue.js jquery-select2