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"
  },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM