简体   繁体   English

为 Vue Select2 包装器组件使用动态 AJAX URL

[英]Use dynamic AJAX URL for Vue Select2 wrapper component

I modified the Wrapper Component Example from the VueJS documentation to include the AJAX datasource option.我修改了 VueJS 文档中的Wrapper Component Example以包含 AJAX 数据源选项。 Here is my code.是我的代码。

However, I would like to set the ajax url property of my select2 component dynamically preferably like this,但是,我想像这样动态设置我的 select2 组件ajax url属性,

<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 :将属性添加到组件的props

     Vue.component('select2', { props: ['options', 'value', 'url'],
  2. Move the AJAX options either to a variable with scope outside the select2 component or a data element of that component:将 AJAX 选项移动到范围在 select2 组件之外的变量或该组件的数据元素:

     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 } }; },
  3. use that variable when initializing the select2:在初始化 select2 时使用该变量:

     mounted: function() { var vm = this $(this.$el) .select2({ placeholder: "Click to see options", ajax: this.ajaxOptions })
  4. Add a watcher for url :url添加一个观察者:

     watch: { url: function(value) { this.ajaxOptions.url = this.url; $(this.$el).select2({ ajax: this.ajaxOptions}); }
  5. Set the property:设置属性:

     <select2 :options="options" v-model="selected" :url="url">

    where url is defined in the data object of the app.其中url在应用程序的数据对象中定义。

See a demonstration in this plunker example .请参阅此 plunker 示例中的演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM