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

Vue项目中无法使用vue-typed-js,引入后路由与插件均失效求助

Vue3中使用vue-typed-js导致路由及插件失效的解决方案

核心原因

你当前安装的vue-typed-js默认是Vue2兼容版本,而你的项目使用的是Vue3(代码里用到了createApp),版本不兼容会导致插件初始化报错,进而阻塞整个应用的初始化流程,路由自然也无法正常工作。

解决步骤

1. 查看控制台报错确认问题

打开浏览器开发者工具的控制台,会看到类似TypeError: Cannot read property 'prototype' of undefined的错误,这是Vue2插件在Vue3中运行的典型报错。

2. 安装Vue3兼容版插件

卸载现有Vue2版本的包,安装适配Vue3的版本:

npm uninstall vue-typed-js
npm install vue-typed-js@next

重新运行项目后,原有的全局注册和组件使用方式即可正常工作。

3. 备选方案:手动封装Vue3组件(更稳定)

如果不想依赖第三方插件的版本兼容问题,可以直接基于typed.js封装自己的Vue3组件,灵活性更高:

首先安装typed.js:

npm install typed.js

然后创建自定义组件TypedText.vue:

<template>
  <div>
    <span ref="typedEl"></span>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import Typed from 'typed.js'

const typedEl = ref(null)
const typedInstance = ref(null)

const props = defineProps({
  strings: {
    type: Array,
    required: true
  },
  typeSpeed: {
    type: Number,
    default: 60
  },
  loop: {
    type: Boolean,
    default: false
  },
  backSpeed: {
    type: Number,
    default: 30
  }
})

onMounted(() => {
  typedInstance.value = new Typed(typedEl.value, {
    strings: props.strings,
    typeSpeed: props.typeSpeed,
    loop: props.loop,
    backSpeed: props.backSpeed
  })
})

// 监听props变化,更新打字效果
watch(props, (newProps) => {
  if (typedInstance.value) {
    typedInstance.value.destroy()
    typedInstance.value = new Typed(typedEl.value, {
      strings: newProps.strings,
      typeSpeed: newProps.typeSpeed,
      loop: newProps.loop,
      backSpeed: newProps.backSpeed
    })
  }
})

onBeforeUnmount(() => {
  if (typedInstance.value) {
    typedInstance.value.destroy()
  }
})
</script>

使用时直接在页面引入:

<template>
  <TypedText :strings="['First text', 'Second Text']" :loop="true" />
</template>

<script setup>
import TypedText from '@/components/TypedText.vue'
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:10:11