javascript - 将 v-if 与在 Vuex 存储中获取值的计算属性一起使用不是响应式的
问题描述
所以我目前正在开发一个 Vue/Nuxt 应用程序,我正在尝试让从移动设备切换到桌面设备并使用 v-if 显示某些元素成为可能。我目前在这个组件中有 v-if:
<template>
<div>
<Search />
<div v-if="device" class="header__mobile-menu-toggle">
<a @click="$emit('openMobileMenu', $event)" href="#" title="Open menu"><i class="fas fa-bars"></i></a>
</div>
<div v-if="device" class="header__mobile-menu-close">
<a @click="$emit('closeMobileMenu', $event)" href="#" title="Sluit menu"><i class="fa fa-times"></i></a>
</div>
</div>
</template>
<script>
import Search from './components/Search.vue';
export default {
props: {
data: Object
},
components: {
Search
},
computed: {
device() {
return this.$store.getters['collection/layout/getDevice'];
}
}
}
</script>
如您所见,我有一个名为“device”的计算属性,它在 default.vue 布局中设置为 false 或 true:
mounted() {
window.addEventListener('resize', this._debounce(determineScreenSize.bind(this), 100))
function determineScreenSize() {
if(window.innerWidth < 1025) {
this.$store.commit('collection/layout/setDevice', true);
}
if(window.innerWidth < 768) {
this.$store.commit('collection/layout/setMobile', true);
}
if(window.innerWidth > 767) {
this.$store.commit('collection/layout/setMobile', false);
}
if(window.innerWidth > 1024) {
this.$store.commit('collection/layout/setDevice', false);
}
}
if(this !== undefined) {
determineScreenSize.apply(this);
}
},
当然,我在 Vuex 存储(模块)中有这个值,它具有适当的突变和吸气剂。
export const state = () => ({
data: {},
isDevice: false,
isMobile: false
})
export default {
getters: {
getDevice: state => {
console.log(state.isDevice);
return state.isDevice
}
getMobile: state => {
return state.isMobile
}
}
, mutations : {
setDevice( state, data ) {
state.isDevice = data
}
setMobile( state, data ) {
state.isMobile = data
}
}
}
在初始页面加载时,一切都按计划进行。如果用户在设备上,它会显示它,如果不是,它不会。但是,正如您在调整大小时看到的那样,它会更改 state.isDevice 和 state.isMobile 属性。但是模板本身不会被 Vue/Nuxt 重新绘制。这有什么原因吗?我是否以完全错误的方式做某事?
提前致谢!
编辑:实际上调用了该函数,这是调整窗口大小几次后使用 VueDevtools 的屏幕截图:
解决方案
推荐阅读
- windows - Perl 如何查看 Windows 快捷方式指向的位置?
- c++ - 提升deadline_timer导致堆栈缓冲区溢出
- python - KML 文件中的批量自动替换字符串
- c++ - Boost::asio async_read 调用 2 次
- angular - CDK拖放可调整大小(角度)的问题
- grails - Grails 4 迁移后无法运行集成测试用例
- r - 将 R 路径转换为 bash 命令的最佳方法是什么?
- tinymce - 从 tinymce 4 到 tinymce 5 的代码迁移 - 动作函数问题(真/假)
- ios - 后台 URLSession 卡住
- c - 消息队列 mq 发送错误。错误的文件描述符