Vue-i18n 多國語言

by on # javascript

CDN

https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js
https://cdnjs.cloudflare.com/ajax/libs/vue-i18n/8.0.0/vue-i18n.min.js

HTML

<div id="app">
  <nav>
    <span>Language:</span>
    <button @click="changeLan('en')"></button>
    <button @click="changeLan('tw')"></button>
    <button @click="changeLan('cn')"></button>
    <button @click="changeLan('jp')"></button>
  </nav>
  <h1 v-html="$t('message.hello')"></h1>
  <h1 v-html="$t('message.name')"></h1>  
</div>

CSS

*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

nav{
  display: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
  background-color: #555;
  color: #fff;
  line-height: 50px;
}

nav>span{
  padding-left: 10px;
}

button{
  width: 32px;
  height: 32px;
  line-height: 32px;
  border-radius: 50%;  
  background-color: #4CAF50;
  color: #fff;
  border: none;
  margin: 0 4px;
  cursor: pointer;
  outline: none;
}

JavaScript

const messages = {
  en: {
    message: {
      hello: 'Hello',
      name:'Mike'
    }
  },
  tw: {
    message: {
      hello: '哈囉',
      name:'麥克'
    }
  },
  cn: {
    message: {
      hello: '哈啰',
      name:'麦克'
    }
  },
  jp: {
    message: {
      hello: 'ハロー',
      name:'マイク'
    }
  }
}

let i18n = new VueI18n({
  locale: 'tw', //預設繁中
  messages,
})

let vm = new Vue({
  el: '#app',
  i18n,  
  data:{
    
  },
  methods:{
    changeLan(lan){
      i18n.locale = lan;
      console.log(i18n.locale);
    }
  }
})




實作

參考

javascript, Vue-i18n, 多國語言
comments powered by Disqus