Vue集成vue draggable组件后页面空白,报Invalid vnode type错误求助
解决Vue集成Draggable组件后页面空白及"Invalid vnode type"错误
问题描述
自有组件原本运行正常,集成Draggable组件后页面完全空白,报错:
Invalid vnode type when creating vnode: undefined
组件代码如下:
<template> <div :class="['image-select']"> <draggable v-model="images"> <div v-for="image in images" :class="['image-select-image']" :key="image.id"> <input type="hidden" :name="fieldName()" :value="image.id"> <img :src="imageUrl(image,size)" :alt="image.alt"> </div> </draggable> </div> </template> <script setup> import {onBeforeMount, ref} from 'vue'; import api from "../modules/api"; import {draggable} from "vuedraggable"; const props = defineProps({ size: { type: String, default: 'sm' }, name: { type: String, default: 'images' }, selectedValues: { type: Object, default: null } }); const images = ref([]); onBeforeMount(async () => { await Promise.all([ setImages() ]); }); function fieldName(){ return props.name + '[images][]'; } function imageUrl(image, size){ return image.src.replace(/\/[a-zA-Z0-9_\.-]+(\.[a-zA-Z]+)$/,'/'+size+'$1'); } function setImages(){ // load images from ids in selectedValues } </script>
问题原因
核心问题是Draggable组件的导入方式错误:
Vue3版本的vuedraggable采用默认导出,而非命名导出。你当前使用import {draggable} from "vuedraggable"会导致导入的是undefined,模板中使用未定义的组件就会抛出"Invalid vnode type"错误,进而导致页面空白。
另外需确认你安装的是适配Vue3的vuedraggable版本,若安装的是Vue2兼容版本也会引发类似问题。
解决方案
1. 确保安装正确的包版本
如果还未安装或安装的是旧版本,执行以下命令安装Vue3兼容版:
npm install vuedraggable
2. 修正组件导入与模板使用
将导入语句改为默认导入,并确保模板中组件名符合Vue规范:
修改后的<script setup>部分:
import {onBeforeMount, ref} from 'vue'; import api from "../modules/api"; // 改为默认导入,使用大驼峰命名组件 import Draggable from "vuedraggable";
修改后的模板部分:
<Draggable v-model="images"> <div v-for="image in images" :class="['image-select-image']" :key="image.id"> <input type="hidden" :name="fieldName()" :value="image.id"> <img :src="imageUrl(image,size)" :alt="image.alt"> </div> </Draggable>
3. 额外检查点
- 确认
images数组在setImages函数中被正确赋值,避免因数组为空导致视觉上的空白(但这不是本次报错的直接原因)。 - 若使用TypeScript,需确保安装对应的类型声明
@types/sortablejs。
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

