mode 属性
- spa 没有服务器端渲染(只有客户端导航)
- universal 默认 同构应用(服务端渲染+客户端导航)
此属性已被弃用,请使用 ssr: false || true 代替
// nuxt.config.js{//...ssr: true, // 默认是true 代替 mode = universal//...}
Middleware
nuxt Middleware 执行时机
- 当第一次访问nuxt的应用时或刷新页面时
- 在pages/.vue / layouts/.vue 配置了 Middleware时,并跳转到对应路由时
nuxt.config.js 配置了 ssr:false 时 在两种情况下都会在客户端调用中间件
您可以通过在middleware/ 目录中创建一个文件来创建命名中间件 ,文件名将是中间件名称。
中间件将按以下顺序依次执行:
- nuxt.config.js (按文件内的顺序)
- 匹配的布局
- 匹配的页面
中间件可以是异步的。为此,请返回 a Promise 或使用 async/await。
// middleware/stats.jsimport http from 'http'export default function ({ route }) {return http.post('http://my-stats-api.com', {url: route.fullPath})}// nuxt.config.jsexport default {router: {middleware: ['stats']}}// pages/index.vue / layouts/default.vueexport default {middleware: ['stats']}
// 匿名中间件<template><h1>Secret page</h1></template><script>export default {middleware({ store, redirect }) {// If the user is not authenticatedif (!store.state.authenticated) {return redirect('/login')}}}</script>
plugins
plugins 目录包含要在实例化根 Vue.js 应用程序之前运行的 JavaScript 插件。需要配置nuxt.config.js
注意,插件默认会在服务器端和客户端都执行,想要区分他的话
export default {plugins: ['~/plugins/foo.client.js', // only in client side'~/plugins/bar.server.js', // only in server side'~/plugins/baz.js', // both client & server{ src: '~/plugins/client-only.js', mode: 'client' }, // only on client side{ src: '~/plugins/server-only.js', mode: 'server' } // only on server side]}
// plugins/axios.jsexport default function ({ $axios, redirect }) {$axios.onError(error => {if (error.response.status === 500) {redirect('/sorry')}})}// nuxt.config.jsmodule.exports = {modules: ['@nuxtjs/axios'],plugins: ['~/plugins/axios.js']}// pages/index.vue<template><h1>{{ post.title }}</h1></template><script>export default {async asyncData ({ $axios, params }) {const post = await $axios.$get(`https://api.nuxtjs.dev/posts/${params.id}`)return { post }}}</script>
// plugins/vue-tooltip.jsimport Vue from 'vue'import VTooltip from 'v-tooltip'Vue.use(VTooltip)export default {plugins: ['~/plugins/vue-tooltip.js']}
export default {extendPlugins(plugins) { // 调整plugins顺序const pluginIndex = plugins.findIndex(({ src }) => src === '~/plugins/shouldBeFirst.js')const shouldBeFirstPlugin = plugins[pluginIndex]plugins.splice(pluginIndex, 1)plugins.unshift(shouldBeFirstPlugin)return plugins}}
plugin Inject
// plugins/hello.jsexport default ({ app }, inject) => {// Inject $hello(msg) in Vue, context and store.inject('hello', msg => console.log(`Hello ${msg}!`))}// nuxt.config.jsexport default {plugins: ['~/plugins/hello.js']}// demo.vueexport default {mounted() {this.$hello('mounted')// will console.log 'Hello mounted!'},asyncData({ app, $hello }) {$hello('asyncData')// If using Nuxt <= 2.12, use 👇app.$hello('asyncData')}}// store/index.jsexport const state = () => ({someValue: ''})export const actions = {setSomeValueToWhatever({ commit }) {this.$hello('store action')const newValue = 'whatever'commit('changeSomeValue', newValue)}}
Store
nuxt会自定去读store目录,目录中的每个 .js 文件都 store被转换为一个 命名空间模块 (index 作为根模块)
// 可以通过在store/index.js里面加入plugins// import myPlugin from 'myPlugin'// export const plugins = [myPlugin]// 可以关闭严格模式// export const strict = false// store/count.js 使用 this.$store.state.count.counterexport const state = () => ({counter: 0})export const mutations = {increment(state) {state.counter++}}export const actions = {// 如果 nuxtServerInit 在 store 中定义了 action 并且 mode 为 universal,Nuxt.js 将使用上下文调用它(仅从服务器端)。当我们想要直接提供给客户端的服务器上有一些数据时,它很有用。async nuxtServerInit({ commit, dispatch }, { req }) {if (req.session.user) {commit('user', req.session.user)}await dispatch('core/load')}}
预取链接 提前加载 prefetch
Nuxt.js 自动包含智能预取。
<!-- 禁用 prefetch --><NuxtLink to="/about" no-prefetch>About page not prefetched</NuxtLink><NuxtLink to="/about" :prefetch="false">About page not prefetched</NuxtLink>
// nuxt.config.jsexport default {router: {prefetchLinks: false // 全局禁用prefetch// 如果全局禁用了 可以用下面的语句做独立的prefetch// <NuxtLink to="/about" prefetch>About page prefetched</NuxtLink>}}
仅客户端组件
如果您使用的是 Nuxt < v2.5.0版本和vue 版本 < v2.6.0,请使用已弃用的语法
如果您使用的是 Nuxt < v2.9.0 版本,请使用
<template><div><sidebar /><client-only placeholder="Loading..."><!-- this component will only be rendered on client-side --><comments /></client-only></div></template>
有时在服务器渲染网页$refs内
需要注意 this.$nextTick
mounted(){this.initClientOnlyComp()},methods: {initClientOnlyComp(count = 10) {this.$nextTick(() => {if (this.$refs.myComp) {//...} else if (count > 0) {this.initClientOnlyComp(count - 1);}});},}
build dir
.nuxt目录就是所谓的构建目录
// nuxt.config.jsexport default {buildDir: 'nuxt-dist', // 可以通过此选项修改.nuxt的名称,但是记得修改.gitignore文件夹防止它被渲染}
.nuxt 文件夹中:
- router.js 文件是当您将.vue文件放入 pages 文件夹时 Nuxt.js 为您生成的生成的路由器文件。当您想查找为 vue-router 生成哪些路由并找出特定路由的名称时,您可以使用此文件进行调试。
- router.scrollBehavior.js 是你的 Router ScrollBehavior
- Components 文件夹包含所有 Nuxt 组件,例如 NuxtChild 和 NuxtLink。它还包含 nuxt-build-indicator,它是我们在构建应用程序时看到的页面,以及 nuxt-loading,它是我们等待页面加载时看到的加载组件。您还将在此处找到 nuxt-error 页面,其中包含 Nuxt 默认错误页面。
- mixins 文件夹包含 Nuxt$fetch方法所需的文件。
- views 文件夹包含您的应用程序模板和您的服务器错误页面。
- app.js 是您的主要应用程序文件。
- client.js 文件是客户端发生的所有事情所需的客户端文件。
- 对于无操作别名,空文件有意留空
- index.js 文件引导您的应用程序。
- loading.html 是页面加载时使用的文件。
- 中间件文件是保存中间件的地方
- server.js 文件是在服务器上运行的所有代码
- 实用程序包含 Nuxt 工作所需的实用程序。
