Nuxt常用方法总结


一、nuxt添加路由拦截

1. 在plugins文件夹下创建auth.js.

export default ({ app }) => {
    app.router.beforeEach((to, from, next) => {
        // process.client 是否来自客户端渲染
        if (process.client) {
            const token = sessionStorage.getItem('token');
            if (!token && to.path !== '/login') {
                next('/login');
            } else if (to.path !== '/login') {
                next();
            } else {
                next();
            }
        }
    });
};

2.nuxt.config.js页面

plugins: [
    '@/plugins/auth',
  ],

这种做法存在问题: next('/login');会走error页面

解决方案:

1、在middleware文件夹下边创建 redirect.js

export default function ({ route, redirect }) {
  if (process.client) {
    const token = sessionStorage.getItem('token');
    if (!token && route.path !== '/login') {
      redirect('/login');
    }
  }
}

2、nuxt.config.js页面

  router: {
    middleware: ['redirect'],
  },

二、Nuxt 页面 meta 设置

Nuxt.js 为页面提供的特殊配置项。其中 head 配置当前页面的 Meta 标签, 详情参考: https://zh.nuxtjs.org/api/pages-head/

head: {
    title: '一本书 - 首页',
    meta: [
        {
            hid: 'description',
            name: 'description',
            content: 'website description'
        },
        { name: 'keywords', content: '一本书' }
    ]
},

 

三、添加页面切换特效

全局动画默认使用 page 来进行设置,例如现在我们为每个页面都设置一个进入和退出时的渐隐渐现的效果。我们可以先在根目录的 assets/css 下建立一个

main.css 文件。

.page-enter-active, .page-leave-active {
    transition: opacity 2s;
}
.page-enter, .page-leave-active {
    opacity: 0;
}

然后在 nuxt.config.js 里加入一个全局的 css 文件就可以了。

css:['assets/css/main.css'],

四、制作一个详情页

在 Nuxt.js 里面定义带参数的动态路由,需要创建对应的以下划线作为前缀的 Vue 文件 或 目录。也就是要么创建_id.vue,要么创建_id/index.vue

新建 pages/books/_id.vue

五、NUXT项目打包发布

1、首先执行npm run build;

2、将打包好的

.nuxt
static
nuxt.config.js
package.json

这四个文件丢到服务器的某个文件夹中,在服务器上安装node环境

3、在服务器上面执行npm install    npm 如果有错误使用 cnpm

4、在服务器上面执行npm run start

使用nginx做代理,想项目域名代理到localhost:3000上面就阔以用域名直接访问项目了;

六、NUXT修改本地3000默认端口

修改package.json文件 dev

"scripts": {
    "dev": "nuxt --hostname 0.0.0.0 --port 3001",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },