首頁  >  問答  >  主體

實現Vue中無需刷新頁面即可改變頁面方向

我希望當在Pinia中的值發生變化時,也能改變頁面的方向,程式碼運作正常,但頁面會重新載入,我不希望頁面重新載入。

這是我的App.vue

<script setup>
import { useaCountdownStore } from "./stores/countdowns";
import { storeToRefs } from "pinia";

const store = useaCountdownStore();
const { theme, language } = storeToRefs(store);

theme.value === "dark" ? document.documentElement.classList.add("dark") : false; //works
language.value === 'ar' ? document.documentElement.setAttribute('dir','rtl'): false // 需要重新加载页面
</script>

<template>
  <router-view></router-view>
</template>
P粉333395496P粉333395496383 天前570

全部回覆(2)我來回復

  • P粉274161593

    P粉2741615932023-09-12 13:06:04

    需要進行常規資料綁定。在這種情況下,使用一個觀察者來實現。

    watch(
      language,
      value => {
       if (value === 'ar')
         document.documentElement.setAttribute('dir','rtl')
       else 
         document.documentElement.removeAttribute('dir')
      },
      { immediate: true }
    )

    請確保在伺服器端渲染時不要存取document

    回覆
    0
  • P粉317679342

    P粉3176793422023-09-12 09:04:32

    嘗試將您的內容放在另一個元素中,而不是修改document。此外,使用計算屬性進行響應性。

    <script setup>
    import { useaCountdownStore } from "./stores/countdowns";
    import { storeToRefs } from "pinia";
    import { computed } from "vue";
    
    const store = useaCountdownStore();
    const { theme, language } = storeToRefs(store);
    
    const direction = computed(() => language.value === 'ar' ? 'rtl' : 'auto')
    </script>
    
    <template>
      <div :class="theme" :dir="direction">
        <router-view></router-view>
      </div>
    </template>
    

    回覆
    0
  • 取消回覆