vue国际化及换肤

317 阅读1分钟

vue国际化及换肤

国际化

  1. 安装国际化依赖
npm i vue-i18n --save
  1. main.js zh.js en.js
//  main.js
import Vue from 'vue'
import App from './App.vue'

import zh from './i18n/zh'
import en from './i18n/en'

import VueI18n from 'vue-i18n';
Vue.use(VueI18n) // 通过插件的形式挂载
const i18n = new VueI18n({
  locale: 'zh', // 语言标识 //this.$i18n.locale // 通过切换locale的值来实现语言切换
  messages:{
  'zh': {...zh},
  'en': {...en}
  }
});
new Vue({
  i18n,
  render: h => h(App),
}).$mount('#app')

// zh.js
export default {
    lg: {
        name: "保罗"
    }
}
// en.js
export default {
    lg: {
        name: "baoluo"
    }
}
  1. App.vue
<template>
  <div class="hello">
    <button @click="changTheme">切换国际化</button>
    <p>
      {{ $t("lg").name }}
    </p>
  </div>
</template>

<script>
export default {
  name: 'App',
  methods: {
    changTheme() {
      this.$i18n.locale =  this.$i18n.locale === "zh" ? "en" : "zh"
    }
  }
}
</script>

换肤

全局样式文件,所有颜色都应该写在里面,以变量的形式

  1. root.css
:root[theme="黑色"] {
    --defalut-color: white
}

:root[theme="白色"] {
    --defalut-color: black
}
  1. main.js
import Vue from 'vue'
import App from './App.vue'

import "./theme/root.css"

new Vue({
  render: h => h(App),
}).$mount('#app')
  1. App.vue
<template>
  <div class="hello">
    <select v-model="theme" @change="changeTheme">
      <option value="白色">白色</option>
      <option value="黑色">黑色</option>
    </select>
    <p style="color: var(--defalut-color);">
      换肤操作
    </p>
  </div>
</template>

<script>
export default {
  name: 'App',
  created() {
    document.documentElement.setAttribute("theme", "黑色");
  },
  methods: {
    changeTheme() {
      console.log(this.theme);
      document.documentElement.setAttribute("theme", this.theme);
    }
  }
}
</script>