简体   繁体   English

用于翻译的脚本设置中的 Vue3 反应性

[英]Vue3 Reactivity in script setup for translation

I am adding some DOM elements in the script setup side but I want the messages to change when I change the language.我在脚本设置端添加了一些 DOM 元素,但我希望在更改语言时更改消息。 I am using vue-i18n plugin.我正在使用 vue-i18n 插件。 It's easy to do it in the template section because I can basically use the useI18n().t method but how can I do this in the script setup section.在模板部分很容易做到这一点,因为我基本上可以使用 useI18n().t 方法,但我如何在脚本设置部分做到这一点。 Using the useI18n().t method doesn't ensure reactivity.使用 useI18n().t 方法不能确保反应性。

Example Code:示例代码:

$(".time")[0].innerHTML = `
<div>0<span>${useI18n().t("details.hour")}</span></div>
<div>0<span>${useI18n().t("details.minute")}</span></div>
<div>0<span>${useI18n().t("details.second")}</span></div>
`

Manipulating DOM directly inside the script leads to inconsistence in your app, you should drive your component by different reactive data to achieve your goal.直接在脚本中操作 DOM 会导致您的应用程序不一致,您应该通过不同的反应数据驱动您的组件以实现您的目标。 In your current situation try to define a computed property based on the translation then render it inside the template based on its different properties:在您当前的情况下,尝试根据翻译定义计算属性,然后根据其不同属性将其呈现在模板中:

<script setup>


const {t} =useI18n()

const time = computed(()=>{
  return {
    hour:t(""details.hour"),
    minute:t(""details.minute"),
    second:t(""details.second"),
  }
})

</script>
<template>
  <div class="time">
    <div>0<span>{{time.hour}}</span></div>
    <div>0<span>{{time.minute}}</span></div>
    <div>0<span>{{time.second}}</span></div>
  </div>
</template>


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM