Nuxt3如何对顶层div的部分style客户端渲染?
vue版本"^3.5.13",nuxt3版本"^3.16.2"
Nuxt3对于客户端部分的代码可以使用<ClientOnly></ClientOnly>,那如果是要在顶层div读取clientWidth的值呢,那不是得<ClientOnly><div></div></ClientOnly>,那这样岂不是全部都成客户端渲染了。
需求是要在顶层div判断是否宽度小于一定的值,小于一定的值的时候改成页面黑底白字。
以下是代码
<script>
import { ref, onMounted } from 'vue';
const screenWidth = ref(process.client ? document.documentElement.clientWidth : 1000)
onMounted(() => {
if (process.client) {
screenWidth.value = document.documentElement.clientWidth
}
})
</script>
<template>
<div :style="{
...(screenWidth < 822 ? {
backgroundColor: 'black',
color: 'white',
} : { })
}">
</template>
尝试过媒体查询,没有效果
@media (max-width: 821px) {
#app {
background-color: black;
color: white;
}
}
期望能Nuxt3能对顶层div的部分style客户端渲染
写代码,正确的做法是:
不要试,不要遇到问题就马上换方向。
具体到你的问题上:Nuxt 的根结点是
#__nuxt
,你在 DevTools 里看一眼就知道了。