<template>
<div>
<select ref='select'>
<slot></slot>
</select>
</div>
</template>
<script>
import Vue from "vue"
export default {
name: "VueSelect",
props: ['options', 'value'],
mounted: function () {
var vm = this;
$(this.$refs.select)
.select2({
data: this.options,
tags: true,
theme: "bootstrap",
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (state) {
console.log(state)
if (!state.id) {
return state.text;
}
var baseUrl = "/dist/peoples";
var imgUrl = baseUrl + '/' + state.element.value.toLowerCase() + '.png'
var $state = $(
'<span><img src="'+imgUrl+'" class="img-flag" /> ' + state.text + '</span>'
);
return $state;
}
})
.on('change', function (ev, args) {
if (!(args && "ignore" in args)) {
vm.$emit('input', $(this).val());
vm.$emit("change_value",$(this).val())
}
});
Vue.nextTick(() => {
$(this.$refs.select)
.val(this.value)
.trigger('change', { ignore: true })
});
},
methods: {
getImageUrl: function(src) {
return require("~/assets"+src);
}
},
watch: {
value: function (value, oldValue) {
// update value
$(this.$refs.select)
.val(this.value)
.trigger('change', { ignore: true });
},
options: function (options) {
// update options
$(this.$refs.select).select2({ data: options })
}
},
destroyed: function () {
$(this.$refs.select).off().select2('destroy')
}
}
</script>
<style>
.select2-container--default {
min-width: 100%;
}
</style>
Here’s my Vue + Select2 component.
The issue is that I can’t import image dynamically within jQuery script.
var baseUrl = "~/assets/images/peoples";
var imgUrl = baseUrl + '/' + state.element.value.toLowerCase() + '.png'
I have tried as follows according to the Nuxt dynamic import guide
var baseUrl = "~/assets/images/peoples";
var imgUrl = require(baseUrl + '/' + state.element.value.toLowerCase() + '.png')
But it fails.
The console says "Cannot find module "~/assets/images/peoples/10.png" "
also I can’t import using static folder ( I copied them to it) with "var baseUrl = "/static/images/people"
The console says "localhost:3000/static/images/people/10.png" cannot found".
Anyone can help me?
2
Answers
I’m not trying to fully answer your question here but what I know is that if you’re using ‘static’ folder to serve images, you should use it without using the word ‘static’ in your URL. For example:
should be
which will then serve from
I could have commented but my reputation is too low to comment but good enough to submit an answer.
If it’s in static, you only to have
/images/people
as mentioned by Raju. Also, I would recommend quite a simple solution: skip jQuery and use a Vue package for that one rather. You will have a far better API and less bugs overall.Give a try to a well maintained and good matching package here: https://github.com/vuejs/awesome-vue#select
jQuery is too messy, get’s into Vue’s reactivity way of things and is bringing a big load of JS for "nothing" since Vue can make as good with it’s own API.