如何更改 span 标签中的 "card" - Vue.JS?

How to change the "card" in a span tag - Vue.JS?

如果“const local (const local = localStorage.getItem("key");”等于“name_jp”,则将“card.name_en”改为“card.name_jp" 位于 span 标签内。我怎样才能有效和正确地做到这一点?

***对不起我的英语不好

    <div class="b-card" v-for="card in list" :key="card.id">
        <span class="span" id="name">
          <span class="span2">+</span> {{ card.name_en }}</span>
    </div>
    </div>

  </div>
</template>

<script>
import { computed } from "vue";
import { lan } from "@/modules/languages";
import useCards from "@/modules/geral";

export default {
  setup() {
    const cards = useCards();
    const list = computed(() => cards.state.details);
    const local = localStorage.getItem("key");

    return {
      list,
      lan,
      local,
    };

只需为该字段添加计算 getter:

setup() {
  const cards = useCards();
  const list = computed(() => cards.state.details);
  const local = localStorage.getItem("key");

  const localizedName = computed(() => (card) => {
    if (local === 'jp') {
      return card.name_jp
    } else {
      return card.name_en
    }
  })

  return {
    list,
    lan,
    local,
    localizedName,
  };
}

并将其用作:

<span class="span2">+</span> {{ localizedName(card) }}</span>

请注意,更改 localStorage 中的值不会重绘组件。 localStorage.getItem('key') 不是反应式 属性;因此,每次更改都必须伴随着组件的重绘。或者,您可以使用 useLocalStorage from the vueuse 等。这将有助于使 local 值具有反应性:

setup() {
  const cards = useCards();
  const list = computed(() => cards.state.details);
  const local = useLocalStorage("key");

  const localizedName = computed(() => (card) => {
    if (local.value === 'jp') {
      return card.name_jp
    } else {
      return card.name_en
    }
  })

  return {
    list,
    lan,
    local,
    localizedName,
  };
}