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

Vue路由中NProgress is not defined报错,已安装vue-nprogress仍未解决怎么办?

解决Vue项目中NProgress is not defined的问题

Hey there, let's fix this NProgress is not defined error step by step! The issue is that even though you've installed vue-nprogress, you haven't properly imported and registered it in your project, so it's not available in your router hooks.

1. 先确认依赖安装

First, double-check you've installed the correct packages (you mentioned you did, but just to be thorough):

npm install vue-nprogress --save
# 或者如果想直接用原生NProgress:
npm install nprogress --save

2. 全局注册vue-nprogress(推荐项目全局使用)

If you want to use the Vue-wrapped version across your app, register it in your entry file (like app.js or main.js):

// app.js
import Vue from 'vue'
import NProgress from 'vue-nprogress'
import 'nprogress/nprogress.css' // 必须引入样式,不然进度条不会显示

// 注册NProgress插件到Vue
Vue.use(NProgress)

// 创建NProgress实例(可配置父容器等选项)
const nprogress = new NProgress({ parent: '#wrapper' })

// 把NProgress实例传入Vue根实例
const app = new Vue({ 
  el: '#wrapper', 
  router, 
  store,
  nprogress // 关键:添加这一行,让实例全局可用
});

Then update your router.js to access the NProgress instance via the Vue app:

// router.js
router.beforeEach((to, from, next) => {
  router.app.$nprogress.start()
  router.app.$nprogress.set(0.1)
  next()
})

router.afterEach(() => {
  setTimeout(() => router.app.$nprogress.done(), 500)
})

3. 直接使用原生NProgress(更简单,适合仅路由使用)

If you only need NProgress for router transitions, skip the Vue wrapper and use the original nprogress library directly in router.js:

// router.js
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // 别忘了样式!

const router = new VueRouter({ routes, hashbang: false, mode: 'history' })

router.beforeEach((to, from, next) => {
  NProgress.start()
  NProgress.set(0.1)
  next()
})

router.afterEach(() => {
  setTimeout(() => NProgress.done(), 500)
})

This approach avoids any Vue registration issues and gets you up and running quickly.

4. 关键注意事项

  • Don't forget the CSS: Without importing nprogress/nprogress.css, the progress bar won't be visible even if the code works.
  • Check scoping: If you're using a module bundler like Webpack, make sure your imports have no typos in package names or file paths.
  • Vue instance access: When using the vue-nprogress wrapper, you need to pass the instance to the root Vue app to access it in router hooks (since router hooks run outside component context).

内容的提问来源于stack exchange,提问作者Harshith J Poojary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:42:44