nuxt-markdown-blog-starter icon indicating copy to clipboard operation
nuxt-markdown-blog-starter copied to clipboard

Suggestion: add heading tag anchors

Open ninest opened this issue 4 years ago • 0 comments

I realized that the blog didn't have heading anchors, so I thought it'll be a good idea to add to the example.

The markdown-it-anchor plugin can be used.

In nuxt.config.js, add:

import mia from 'markdown-it-anchor';

...

md.use(mia, {
  permalink: true,
});

...

export default {
  ...
  router: {
    scrollBehavior: async (to, from, savedPosition) => {
      if (savedPosition) {
        return savedPosition;
      }

      const findEl = (hash, x = 0) => {
        return (
          document.querySelector(hash) ||
          new Promise((resolve) => {
            if (x > 50) {
              return resolve(document.querySelector('#app'));
            }
            setTimeout(() => {
              resolve(findEl(hash, ++x || 1));
            }, 100);
          })
        );
      };

      if (to.hash) {
        const el = await findEl(to.hash);
        if ('scrollBehavior' in document.documentElement.style) {
          return window.scrollTo({ top: el.offsetTop, behavior: 'smooth' });
        } else {
          return window.scrollTo(0, el.offsetTop);
        }
      }

      return { x: 0, y: 0 };
    }
  }
};

Anchors seem to be broken in Nuxt, so you need to add the scrollBehavior function. Check this issue: #5359

Another reason why this might be a good idea to add is because anchors don't work in Nuxt. This may help beginners.

Apart from this, I'd also like to thank you for creating this example! It's perfect!

ninest avatar May 24 '20 14:05 ninest