[Vuejs]-Trying to use Select2 in a Vue Component, but options are blank?

0👍

subdomains can not be passed to select2 directly, select2‘s data format should be like {id:"", text:""}. below is a worked version based on your code.

<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
<div id="app">
    <select2 :subdomains="choices" v-model="subdomain">
      <option disabled value="0">Select one</option>
    </select2>
</div>
<script type="text/x-template" id="select2-template">
  <select>
    <slot></slot>
  </select>
</script>
<script>
function select2data(subdomains) {
    return subdomains.map((d)=>({id:d.character_code, text:d.character_code}));
}

Vue.component("select2", {
    props: ["subdomains", "value"],
    template: "#select2-template",
    mounted: function() {
        var vm = this;
        let s2 = $(this.$el)
            // init select2
            .select2({ data: select2data(this.subdomains), width: '200px'})
            // emit event on change.
            .on("change", function(val) {
                vm.$emit("input", vm.subdomains.find((d)=>d.character_code == this.value));
            });
    },
    watch: {
        value: function(value) {
            // update value
            if (value && value.character_code != this.$el.value) {
                $(this.$el).val(value.character_code);
            }
        },
    subdomains: function(subdomains) {
        // update subdomains
        $(this.$el)
          .empty()
          .select2({ data: select2data(subdomains) });
      }
    },
    destroyed: function() {
        $(this.$el)
            .off()
            .select2("destroy");
    }
});

let subdomains = [{
      "other_fields":"xxxxxxx",
      "character_code": "abc.com"
    },
    {
      "other_fields":"oooooooo",
      "character_code": "efg.com"
    }];

let app = new Vue({
  el: '#app',
  data: {
    choices:subdomains,
    subdomain:subdomains[0]
  },
  watch:{
    subdomain:function(newVal) {
        console.log('subdomain changed', newVal.character_code);
    }
  }
});
</script>
</body>
</html>

Leave a comment