所以我目前正在开发一个 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 的屏幕截图:
