VueJS 3 组合中的Select2

问题描述 投票:0回答:1

如何在组合VueJs3中创建select2组件?

我正在学习新的 VueJS 3,当我想创建 select2 组件时,出现错误,请帮我修复它。我之前在 vueJS 2 上尝试过代码并且它可以工作。

我的组件文件:

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import 'select2'
import $ from 'jquery'

const element = ref();
const options = ref<Option[]>([
    {
        key: 1,
        value: 'a'
    },
    {
        key: 2,
        value: 'b'
    },
    {
        key: 3,
        value: 'c'
    }
])


onMounted(() => {
    $(element.value).select2()
})
</script>

<template>
    <select ref="element" class="form-control">
        <option :value="option.key" v-for="option in options">{{ option.value }}</option>
    </select>
</template>

我的控制台上出现错误:

我安装的是:

{
  "name": "learn-3.0",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "preview": "vite preview --port 5050",
    "test:unit": "vitest --environment jsdom",
    "typecheck": "vue-tsc --noEmit -p tsconfig.vitest.json --composite false",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
  },
  "dependencies": {
    "axios": "^0.26.1",
    "bootstrap": "^5.1.3",
    "inputmask": "^5.0.7",
    "jquery": "^3.6.0",
    "node-snackbar": "^0.1.16",
    "pinia": "^2.0.11",
    "select2": "^4.1.0-rc.0",
    "select2-bootstrap-5-theme": "^1.2.0",
    "vue": "^3.2.31",
    "vue-router": "^4.0.12"
  },
  "devDependencies": {
    "@rushstack/eslint-patch": "^1.1.0",
    "@types/inputmask": "^5.0.3",
    "@types/jquery": "^3.5.14",
    "@types/jsdom": "^16.2.14",
    "@types/node": "^16.11.25",
    "@types/select2": "^4.0.55",
    "@vitejs/plugin-vue": "^2.2.2",
    "@vue/eslint-config-prettier": "^7.0.0",
    "@vue/eslint-config-typescript": "^10.0.0",
    "@vue/test-utils": "^2.0.0-rc.18",
    "@vue/tsconfig": "^0.1.3",
    "eslint": "^8.5.0",
    "eslint-plugin-vue": "^8.2.0",
    "jsdom": "^19.0.0",
    "prettier": "^2.5.1",
    "sass": "^1.49.9",
    "typescript": "~4.5.5",
    "vite": "^2.8.4",
    "vitest": "^0.5.0",
    "vue-tsc": "^0.31.4",
    "webpack": "^5.70.0"
  }
}

jquery vuejs3 jquery-select2
1个回答
0
投票

select2 应该像这样导入:

从'select2'导入select2;

并且在使用.select2()之前,必须执行select2()函数:

<script setup lang="ts"> 
import { onMounted, ref } from 'vue'; 
import select2 from 'select2';
import $ from 'jquery';

const element = ref(); const options = ref<Option[]>([
    {
        key: 1,
        value: 'a'
    },
    {
        key: 2,
        value: 'b'
    },
    {
        key: 3,
        value: 'c'
    } ])

select2();

onMounted(() => {
    $(element.value).select2() 
}) 
</script>

© www.soinside.com 2019 - 2024. All rights reserved.