我希望当在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> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
需要进行常规数据绑定。在这种情况下,使用一个观察者来实现。
watch( language, value => { if (value === 'ar') document.documentElement.setAttribute('dir','rtl') else document.documentElement.removeAttribute('dir') }, { immediate: true } )请确保在服务器端渲染时不要访问
document。尝试将您的内容放在另一个元素中,而不是修改
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>