You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3使用vue-tiny-slider报错't2 is not a function'求解决方案

Vue3 中使用 vue-tiny-slider 出现 't2 is not a function' 错误的解决方案

我在Vue3项目中安装了vue-tiny-slider,但运行时出现报错:Uncaught (in promise) TypeError: t2 is not a function。由于组件文档未覆盖Vue3的配置方法,我自行尝试了配置,以下是我的模板和脚本代码,希望找到可行的解决办法。

模板代码

<template>
    <div class="my-slider">
        <vue-tiny-slider
            :mouse-drag="true"
            :loop="false"
            :items="2"
            :gutter="20">
            <div
                v-for="recipe in storeRecipe.popularRecipes"
                :key="recipe.recipe_id">
                <ItemCard :recipe="recipe" :pending="storeRecipe.pending" />
            </div>
        </vue-tiny-slider>
    </div>
</template>

脚本代码

<script setup>
import ItemCard from '@/component/ItemCard.vue';
import { onMounted, h } from 'vue';
import { useStoreRecipe } from '@/store/storeRecipe';
const storeRecipe = useStoreRecipe();

import VueTinySlider from 'vue-tiny-slider';

const render = () => {
    return h(
        VueTinySlider,
        {},
        {
            default: () => (this.$slots.default ? this.$slots.default() : []),
        }
    );
};

onMounted(async () => {
    render();
    await storeRecipe.loadPopularRecipes();
});
</script>

问题分析

原vue-tiny-slider是为Vue2设计的,直接在Vue3的<script setup>中使用会存在兼容性问题,当前代码的核心问题:

  1. <script setup>中不存在this上下文,你写的this.$slots完全无效
  2. 手动调用render()的方式不符合Vue3组件渲染逻辑,组件应直接在模板中声明
  3. 未适配Vue3的组件注册与插槽处理机制

可行解决方案

方案一:使用Vue3适配版组件(推荐)

直接使用社区维护的Vue3兼容版vue3-tiny-slider,API与原组件完全一致,无需额外适配:

  1. 安装适配包
npm install vue3-tiny-slider
  1. 修改代码
    模板保持不变,脚本部分调整为:
<script setup>
import ItemCard from '@/component/ItemCard.vue';
import { onMounted } from 'vue';
import { useStoreRecipe } from '@/store/storeRecipe';
const storeRecipe = useStoreRecipe();

// 导入Vue3适配版组件
import VueTinySlider from 'vue3-tiny-slider';

onMounted(async () => {
    await storeRecipe.loadPopularRecipes();
});
</script>

方案二:手动适配原组件(仅作参考)

如果一定要用原vue-tiny-slider包,需手动封装适配Vue3的组件:

<script setup>
import ItemCard from '@/component/ItemCard.vue';
import { onMounted, h, defineComponent } from 'vue';
import { useStoreRecipe } from '@/store/storeRecipe';
const storeRecipe = useStoreRecipe();

import VueTinySlider from 'vue-tiny-slider';

// 封装适配Vue3的组件
const Vue3TinySlider = defineComponent({
  props: VueTinySlider.props,
  setup(props, { slots }) {
    return () => h(VueTinySlider, props, slots);
  }
});

onMounted(async () => {
    await storeRecipe.loadPopularRecipes();
});
</script>

模板中把<vue-tiny-slider>替换为<Vue3TinySlider>即可。


内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:10:29