我的一个布局中有以下代码。
bodyAttrs: {
class: this.$store.state.user.theme + '-scheme'
}
不幸的是,我使用的是旧的bootstrap主题css。我不想重做它,因此我必须弄清楚一些工作。
引导主题的主题颜色将自身附加到body标签。不幸的是身体标签是nuxt中的no no。
我注意到的是,刷新后页面将使用基本状态值进行渲染。
例如:
//store/index.js <- not modular
var state = () => ({
user: {
id: 0,
avatar: 'default.jpg',
status: 'offline',
nickname: 'Guest',
admin: false,
theme: 'brownish' //-> this is the value
}
})
整个页面呈现用户详细信息,但主题变量未放入渲染中。如果我转到另一个页面(ajax路由),页面将使用正确的颜色更新。
本质上,页面加载棕色,然后在后续页面上加载蓝色。如果刷新页面,则颜色将恢复为棕色,然后在后续页面上将再次变为蓝色。
如何让SSR显示正确的bodyAttr?
我正在使用vuex-persistedstate和cookie都是客户端nuxt服务器没有任何会话,因为这是在一个单独的域(api)上处理
我无法找到纯粹的vuejs方法来做到这一点,所以我做了一个修复。
这在技术上是一个坏主意,因为它直接修改了DOM,这是一个禁忌的。但是,vue不对身体标签使用反应性。因此我觉得使用起来相当安全。此外,使用vuex-presistedstate将确保vue在后续加载时设置正确的状态变量。
//这是layouts / default.vue
head() {
return {
bodyAttrs: {
class: this.$store.state.user.theme + '-scheme'
}
}
},
mounted() {
window.onNuxtReady(() => {
document.body.className = this.$store.state.user.theme + '-scheme'
})
}
您使用的是基于cookie的vuex-persistedstate版本吗? Customize Storage请记住在nuxt.config.js中为插件启用ssr模式