0

I'm currently learning VueJS 3 with typescript language, and I want to create a select2 component, but I got the error that console.log says:

console.log getting error

Here is my code in the AppSelect2.vue file:

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import type { Options } from '../../interfaces';

import 'select2'
import $ from "jquery";


const emit = defineEmits<{
    (e: 'update:modelValue', value: string | number): void
}>()

interface Props {
    id?: string,
    label?: string,
    modelValue: string | number,
    options: Array<Options>,
}

const {
    id,
    label = '',
    modelValue,
    options,
} = defineProps<Props>()

function updateValue(e: Event): void {
    emit("update:modelValue", (e.target as HTMLSelectElement).value)
}

const select = ref(null)

function attach(): void {
    $(select).select2()
}

onMounted(function () {
    setTimeout(() => {
        attach()
    }, 100)
})
</script>

<template>
    <label v-if="label" :for="id" class="form-label">{{ label }}</label>
    <select ref="select" :id="id" class="form-select" v-model="modelValue" @change="updateValue">
        <option v-for="option in options" :value="option.key">{{ option.value }}</option>
    </select>
</template>

and I've installed these packages:

enter image description here

Any helps please?

4
  • select2 is jquery plugin. You didn't import it Commented Mar 21, 2022 at 9:24
  • I did sir. check my AppSelect2.vue code I'm importing jquery as $ Commented Mar 21, 2022 at 11:14
  • You import jquery, not select2. jquery itself doesn't have select2 method. Commented Mar 21, 2022 at 13:17
  • You need to import jquery before select2 Commented Jan 21, 2023 at 20:20

1 Answer 1

1

Have you tried importing the function directly?

import select2 from 'select2';

And then calling it:

$('select').select2()

Instead you could try:
https://www.npmjs.com/package/vue-select2

Which is the same thing, but specifically for vueJS.

There's someone with the same issue here:
https://forums.select2.org/t/select2-in-vue-js/623

Sign up to request clarification or add additional context in comments.

4 Comments

I did, but still got same error
Offered an alternative in my answer, sorry i can't be of more help :(
it's okay and thank you. I'm still trying how It can be done with typescript, I've created select2 in Vue js 2 before, but now, still getting errors with typescript Vue js 3
You also need to import $ otherwise it will not be recognized. Another thing, you suggested a package that was last updated 6 years ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.