Good luck opening the book.

Recently, I used Nuxt to write a CROSS-BORDER e-commerce PC project. It was used for the first time, and a pit was recorded here. If not welcome to discuss guidance.

We often use NProgress for transitions in navigational guards in normal Vue projects, so it was natural to want to do the same in Nuxt. Nuxt has its own loading configuration, so you can call the built-in Progesss in the component. The official example code is as follows:

//nuxt.config.js
export default {
  loading: true
}

//your component
export default {
  mounted() {
    this.$nextTick(() = > {
      this.$nuxt.$loading.start()
      setTimeout(() = > this.$nuxt.$loading.finish(), 500)}}}Copy the code

But this instance doesn’t make sense to me because it’s just a fake loading that is automatically hidden after 500ms. I would prefer to be linked to the progress of the route, which is used in the route guard. So the default loading may not work for us.

So how do you use route guards in Nuxt? In plugins (there may be a better way but I didn’t know it the first time), add a JS file to the plugins folder of your project and load it automatically once configured. The plugins folder represents a large plugin, and your files are part of that pluginThe plug-in configuration, and the final run time automatically merges the load.Basically seerouter-nprogress.js, the code is very simple, as follows:

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
export default ({app}) => {
    app.router.beforeEach((to, from, next) = > {
        NProgress.start()
        next()
    });

    app.router.afterEach(() = > {
        NProgress.done()
    });
}
Copy the code

This is very familiar, many online articles are written here, but after testing found that there are problems. Find the problem here: Their plugin configuration:

//nuxt.config.js
export default {
	plugins: [
    	  // Other irrelevant files are ignored
    	  '~/plugins/router-nprogress.js']}Copy the code

If run, this error is reported

pc\node_modules\nprogress\nprogress.js:267return !! document.getElementById('nprogress'); ^ReferenceError: document is not defined
Copy the code

If the DOM object does not exist, it is likely to be reported by the Node environment. If you look carefully at the above plug-in configuration document, you will find that the plug-in can be configured as a Client or Server plug-in, so the configuration needs to specify the environment:

//nuxt.config.js
export default {
	plugins: [
    	  // Other irrelevant files are ignored
    	   { src: '~/plugins/router-nprogress.js'.mode: 'client' }
           / / or
    	   //{ src: '~/plugins/router-nprogress.js', ssr: false }]}Copy the code

That is, it is generated and used only on the client, but not on the server.

After testing this, it can be used normally. Other configurations of NProgress will not be mentioned.

Finally, an interesting comment I just saw on weibo