Vue3 Element Plus 将 el-pagination设置为中文

1 阅读1分钟

Vue3 Element Plus 将 el-pagination设置为中文

1、安装 Element Plus

npm install element-plus

2、引入中文语言包并配置

在main.ts引入中文包

import { createApp } from 'vue'
import {createPinia} from 'pinia'
import './style.css'
import App from './App.vue'
import router from './router/index.ts'
import 'element-plus/dist/index.css'
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';  // 引入中文语言包

const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(ElementPlus, {locale: zhCn})
app.mount('#app')

3、使用el-pagination插件

  <el-pagination
      v-if="total > 0"
      v-model:current-page="query.page"
      v-model:page-size="query.size"
      class="pagination"
      layout="total, sizes, prev, pager, next"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />
<script setup lang="ts" name="Projects">
    const total = ref(0)
    const query = reactive({
      page: 1,
      size: 10,
	})
	
	function handlePageChange(page: number) {
      query.page = page
      //其他操作
    }

    function handleSizeChange(size: number) {
      query.page = 1
      query.size = size
      //其他操作
    }
</script>

4、中英文切换

1.安装 vue-i18n

npm install vue-i18n@latest

2.在main.ts加入下面配置

import { createApp } from 'vue'
import {createPinia} from 'pinia'
import './style.css'
import App from './App.vue'
import router from './router/index.ts'
import 'element-plus/dist/index.css'

import { createI18n } from 'vue-i18n';
import ElementPlus from 'element-plus';


// main.ts
export const i18n = createI18n({
  locale: 'zh-cn',
  fallbackLocale: 'zh-cn',
  legacy: false,        // 必须为 false
  globalInjection: true, //  允许在非 setup 上下文中也能使用
  messages: {
    'zh-cn': {
      switchLang: '切换英文',
      welcome: '欢迎使用',
    },
    en: {
      switchLang: 'Switch to Chinese',
      welcome: 'Welcome',
    },
  },
})
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(i18n)
app.use(ElementPlus)
app.mount('#app')

3.在app.vue页面加载

<template>
  <el-config-provider :locale="epLocale">
    <router-view></router-view>
  </el-config-provider>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import enUs from 'element-plus/es/locale/lang/en'

const { locale } = useI18n()

// 根据当前 i18n locale 动态映射到 EP 语言包
const epLocale = computed(() => {
  return locale.value === 'zh-cn' ? zhCn : enUs
})
</script>

4.在需要切换的页面进行切换操作

import { useI18n } from 'vue-i18n'

const { locale, t } = useI18n()

const toggleLanguage = () => {
  locale.value = locale.value === 'zh-cn' ? 'en' : 'zh-cn'
}