With Nuxt.js and full static you can now use live preview out of the box which will call your API or your CMS so you can see the changes live before deploying.

Preview Mode - 图1

Only available when using target:static

The preview mode will automatically refresh the page data as it uses $nuxt.refresh under the hood and therefore calls nuxtServerInit, asyncData and fetch on the client side.

In order to activate live preview you will need to add the following plugin:

plugins/preview.client.js

  1. export default function ({ query, enablePreview }) {
  2. if (query.preview) {
  3. enablePreview()
  4. }
  5. }

Preview Mode - 图2

`enablePreview` is only available in the context object of plugins. Previews are handled client-side and thus the plugin should be run on the client: preview.client.js

nuxt.config.js

  1. export default {
  2. plugins: ['~/plugins/preview.client.js']
  3. }

Once you have added the plugin you can now generate your site and serve it.

  1. npx nuxt generate
  2. npx nuxt start
  1. yarn generate
  2. yarn start

Then you can see your preview page by adding the query param to the end of the page you want to see once:

  1. ?preview=true

Preview Mode - 图3

enablePreview should be tested locally with yarn start and not yarn dev

Previewing pages that are not yet generated

For pages that are not yet generated, SPA fallback will still call the API before showing the 404 page as these pages exist on the API but are not generated yet.

If you have set a validate hook, you will probably need to modify it so that it doesn’t redirect to the 404 page in preview mode.

  1. validate({ params, query }) {
  2. if (query.preview) {
  3. return true
  4. }

Passing data to enablePreview

You can pass data to the enablePreview function. That data will then be available on the $preview context helper and on this.$preview.

What’s next

Preview Mode - 图4

Check out the Directory Structure book