nuxt部署、國際化、代理

pages 目錄

Nuxt.js 會依據 pages 目錄中的所有 *.vue 文件

部署

upstream nodenuxt {
    server 127.0.0.1:3000;
    keepalive 64;
}

server {
    listen 80;
    server_name www.demo.com;
    client_max_body_size 10M;

   location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Nginx-Proxy true;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://nodenuxt;
    }
}

發起跨域請求

npm i @nuxtjs/proxy -D

 modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/api': {
      target: 'http://example.com',
      pathRewrite: {
        '^/api' : '/'
      }
    }
  }

國際化

使用vue-i18n進行國際化設置

~/nuxt.config.js

// 引入插件
 plugins: [
    '~/plugins/i18n.js'
  ],
 build: {
    transpile: [/^element-ui/],
    vendor: ['vue-i18n'],
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      
    }
  },

plugins/i18n

// 插件中使用vue-i18n庫
import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
export default ({ app, store }) => {
  // Set i18n instance on app
  // This way we can use it in middleware and pages asyncData/fetch
  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: 'zh',
    messages: {
      'en': require('~/locales/en.json'),
      'zh': require('~/locales/zh.json')
    }
  });
  app.i18n.path = (link) => {
    if (app.i18n.locale === app.i18n.fallbackLocale) {
      return `/${link}`
    }

    return `/${app.i18n.locale}/${link}`
  }
}

配置語言json文件(~locales/zh.json | ~locales/en.json)

// en.json
{
  "mails": {
    "one": "Business Mail",
    "two": "Recruit Mail"
  },
}
// zh.json
{
  "mails": {
    "one": "業務郵箱",
    "two": "招聘郵箱"
  },
}

頁面中使用配置

// index.vue
{{ $t('mails.one', $store.state.locale ) }}:Mail@lang.com
{{ $t('mails.two', $store.state.locale ) }}:Recruit@lang.com

使用vuex進行切換語言

// store/index.js
export const state = () => ({
  locales: ['zh', 'en'],
  locale: 'zh'
})
export const mutations = {
  SET_LANG(state, locale) {
    if (state.locales.indexOf(locale) !== -1) {
      state.locale = locale
      console.log('state.locale', state.locale)
    }
  }
}
// index.vue
change() {
  const locale = this.$store.state.locale;
  let lang;
  lang = locale === 'zh' ? 'en' : 'zh';
  this.$store.commit('SET_LANG', lang);
  window.localStorage.setItem('locale', lang); 
}

參考鏈接

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。