问题
I modified the Wrapper Component Example from the VueJS documentation to include the AJAX datasource option. Here is my code.
However, I would like to set the ajax
url
property of my select2 component dynamically preferably like this,
<select2 :options="options" v-model="selected" url="dynamic-url-here">
<option disabled value="0">Select one</option>
</select2>
How would I do this?
回答1:
Add the property to the Component's
props
:Vue.component('select2', { props: ['options', 'value', 'url'],
Move the AJAX options either to a variable with scope outside the select2 component or a data element of that component:
Vue.component('select2', { props: ['options', 'value', 'url'], template: '#select2-template', data: function() { return { ajaxOptions: { url: this.url, dataType: 'json', delay: 250, tags: true, data: function(params) { return { term: params.term, // search term page: params.page }; }, processResults: function(data, params) { params.page = params.page || 1; return { results: data, pagination: { more: (params.page * 30) < data.total_count } }; }, cache: true } }; },
use that variable when initializing the select2:
mounted: function() { var vm = this $(this.$el) .select2({ placeholder: "Click to see options", ajax: this.ajaxOptions })
Add a watcher for url:
watch: { url: function(value) { this.ajaxOptions.url = this.url; $(this.$el).select2({ ajax: this.ajaxOptions}); }
Set the property:
<select2 :options="options" v-model="selected" :url="url">
where
url
is defined in the data object of the app.
See a demonstration in this plunker example.
来源:https://stackoverflow.com/questions/46425172/use-dynamic-ajax-url-for-vue-select2-wrapper-component