switchLocales.vue 2.44 KB
<template>
  <view style="padding:24rpx;background: #f8f9fa;height: 100vh;">
    <view class="center">
      <view v-for="(item, index) in languageData" :key="item.value" class="flex justify-between"
        :class="index == 0 ? 'v-label' : ''" @click="handleChange(item.value)">
        <view>{{ item.label }}</view>
        <image v-if="language === item.value" class="image" src="/static/languageSelect.png"></image>
      </view>
      
    </view>
  </view>
</template>

<script>
export default {
  onLoad() {
    this.getLocale()
  },
  data() {
    return {
      language: 'zh-CN',
      languageData: [
        { label: '中文简体', value: 'zh-CN' },
        { label: 'English', value: 'en' }
      ]
    }
  },
  onShow() {
    this.$nextTick(() => {
      uni.setNavigationBarTitle({
        title: this.$t('menu.languageSettings')
      })
    })
  },
  methods: {
    getLocale() {
      const locale = uni.getLocale()
      if (locale) {
        this.language = locale.includes('zh')?'zh-CN' : locale
      }
    },
	
    handleChange(name) {
      //App会重启应用
     // #ifdef APP-PLUS || APP
     uni.showModal({
        title:this.$t('userCenter.switchRestLanguage'),
        success:(res)=>{
          if(res.confirm){
            this.$i18n.locale = name
            this.language = name
            uni.setNavigationBarTitle({
              title: this.$t('menu.languageSettings')
            })
            // setLocale设置的语言需要对照到uniapp上的默认配置语言来设置
            uni.setLocale(name.includes('zh')?'zh-Hans':'en')
          }
        }
      })
			// #endif
     // #ifdef MP-WEIXIN
      uni.showLoading({
        title:this.$t('userCenter.switchLanguages')
      })
      const timeOut = setTimeout(()=>{
        this.$i18n.locale = name
        this.language = name
        uni.setNavigationBarTitle({
          title: this.$t('menu.languageSettings')
        })
        uni.setLocale(name.includes('zh')?'zh-Hans':'en')
        uni.hideLoading()
        clearTimeout(timeOut)
      },500)
      // #endif
     
    }
  }
}
</script>

<style scoped lang="scss">
.center {
  background: #fff;
  padding: 24rpx;
  border-radius: 24rpx;

}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.v-label {
  border-bottom: 1rpx solid #ecedee;
  padding-bottom: 6rpx;
  margin-bottom: 8rpx
}

.image {
  width: 44rpx;
  height: 44rpx;
  // margin-top: 20rpx;
  // border-radius: 32rpx;
}
</style>